How can you organize and save models in Three.js in the order they are loaded/called?

When loading models, I want to ensure they are placed in the object array in the same order as they are called. However, sometimes they get assigned a different number and end up in a different sequence.

Is there a way to guarantee that the models are placed in the order they are called to load?

var models = {
    tile: [],
    building: [],
    character: []
};

const loader = new GLTFLoader();
function loadGLTF(path, type){
    loader.load(
        path,
        (gltf) => {
            gltf.scene.traverse( ( node ) => {
                if( node.material ) {
                    node.material.metalness = 0;
                }
                if ( node.isMesh ) {
                    if(type == 'tile'){
                        node.castShadow = false;
                    }
                    else {
                        node.castShadow = true;
                    }
                    node.receiveShadow = true;
                }
            } );
            
            gltf.animations; // Array<THREE.AnimationClip>
            gltf.scene; // THREE.Group
            gltf.scenes; // Array<THREE.Group>
            gltf.cameras; // Array<THREE.Camera>
            gltf.asset; // Object
            
            models[type].push(gltf);
            loading++;
            checkLoad();
        },
        (xhr) => {
            console.log( ( xhr.loaded / xhr.total * 100 ) + '% loaded' );
        },
        (error) => {
            console.log( 'Error: ' + error);
        }
    );
}

/**Load Models**/
//Tiles
loadGLTF('resources/models/tiles/tile_000.glb', 'tile'); //Place in tile[0]
loadGLTF('resources/models/tiles/tile_001.glb', 'tile'); //Place in tile[1]
//Buildings
loadGLTF('resources/models/buildings/building_000.glb', 'building'); //Place in building[0]
loadGLTF('resources/models/buildings/building_001.glb', 'building'); //Place in building[1]
loadGLTF('resources/models/buildings/building_002.glb', 'building'); //Place in building[2]
loadGLTF('resources/models/buildings/building_003.glb', 'building'); //Place in building[3]
loadGLTF('resources/models/buildings/building_004.glb', 'building'); //Place in building[4]
loadGLTF('resources/models/buildings/building_005.glb', 'building'); //Place in building[5]
loadGLTF('resources/models/buildings/building_006.glb', 'building'); //Place in building[6]
loadGLTF('resources/models/buildings/building_007.glb', 'building'); //Place in building[7]
loadGLTF('resources/models/buildings/building_008.glb', 'building'); //Place in building[8]
//Character
loadGLTF('resources/models/characters/Male.glb', 'character'); //Place in character[0]

Answer №1

Before loading the model, you can save the position where the model should be placed in the array and then reference that position after the model has loaded.

const loadingCount = {
  tile: 0,
  building: 0,
  character: 0,
}

function loadGLTF(path, type){
  const modelIndex = loadingCount[type];
  loadingCount[type] += 1;
  loader.load(
    path,
    (gltf) => {
      models[type][modelIndex] = gltf;
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Incorporating a hyperlink within a confirmation return statement

Looking to include a link within a return confirmation <a onclick="return confirm('Make sure you've read our policies before downloading the App');">[...] The policies should be clickable at the end. ...

Navigating through div elements using arrow keys in Vue

Trying to navigate through div elements using arrow keys is proving to be a challenge for me. I have successfully achieved it in JavaScript, but I am facing difficulties doing it the "vue way". Although there should be no differences, it simply does not wo ...

Can you explain the significance of "javascript:void(0)"?

<a href="javascript:void(0)" id="loginlink">login</a> The usage of the href attribute with a value of "javascript:void(0)" is quite common, however, its exact meaning still eludes me. ...

What is the best way to implement date range filtering in vue js?

Currently, I am delving into the realm of vue.js and experimenting with a filtering feature that involves date ranges. The process goes like this: initially filter by type, then proceed to filter by a specified date range, consisting of start and end dat ...

What could be the reason for the absence of this modal?

I'm trying to create a modal that will be shown to users when they use the command modal. Can anyone help me troubleshoot this code? const { MessageActionRow, Modal, TextInputComponent } = require('discord.js'); client.on('interactionC ...

Build an equilateral triangle with the power of three.js

I'm currently working on creating an equilateral triangle using three.js, but it seems like what I've created is a bit too tall. My vertices are defined as follows: new THREE.Vector3(0, 0, 0), new THREE.Vector3(4, 0, 0), new THREE.Vector3(2, 4, ...

Styling the file input type in AngularLearn how to customize the

I've come across numerous queries on how to style an input type file, but I'm struggling to implement it in an angular context. So, what is the best way to customize the appearance of an input type file within an angular application? Below is t ...

Is there a way to reverse the process of Date.parse?

After converting a date to a number with the following code: Date.parse(doc.createdAt); I receive this result: 1576699528000 It seems like the number becomes a string when passed from the server to the front end and back to the server. How can I conver ...

Determining the current element's index as I scroll - using Jquery

If I have a series of divs with the class name 'class' that are fixed height and enable auto-scrolling, how can I determine the index of the current 'class' div I am scrolling in? Here is an example: var currentIndex = -1; $(window).sc ...

Exploring the Differences in Site Navigation: PHP/HTML, Ajax, and CSS/Javascript

Lately, I've been weighing the pros and cons of using AJAX for my website navigation to transfer only necessary updated HTML elements. Alternatively, if there isn't a significant difference between new elements and current ones, just loading the ...

When I utilize $router.push() to navigate to a different page, the back button will take me back to the previous page

Within my Vue project, there is an HTML page that I am working on. Here is the link to the page: https://i.sstatic.net/cbtqM.png Whenever I click on the "+"" button, it redirects me to this specific page: https://i.sstatic.net/0rmMD.png This page funct ...

"An error occurred stating that _co.JSON is not defined in

During my attempt to convert an object into a string using the JSON method, I encountered an error upon loading my page: Error: _co.JSON is undefined The stacktrace for this error message is extensive and seems unnecessary to include at this point. Th ...

Troubleshooting Issues with Form Inputs in JS/Angular Using Places API and document.getElementById Method

I have integrated the Google Places API to automatically populate locations/destinations into a form after a user searches. The auto-population works correctly, but I am facing an issue when trying to submit the form into my database – the object is alwa ...

Is the JSON data missing from the POST request?

I'm having trouble inserting data into the database using a POST request. Here is how I'm making the request: 127.0.0.1:3000/api/users?fname=asd&lname=edc&<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d7870 ...

I am facing an issue where both curl and file_get_contents are not functioning properly after

When attempting to access a user's city information using coordinates, I have encountered an issue with the response not being displayed in my console. The process involves a javascript function that takes latitude and longitude data, sends it to a PH ...

What is the process for retrieving a documentDB document using Azure functions?

After setting up an Azure function and a DocumentDB database with a users collection, I find myself at a roadblock trying to establish the connection between the two. My intention is to input a username and have the function automatically retrieve the corr ...

Obtaining values from multi-dimensional arrays with JavaScript and node.js

I have a data structure like this: let arr = [ ['animal','lion'], ['plant','rose'], ['tree','coconut'], ] I want to reformat it to look like this: ['animal','lion' ...

Inexplicably, HighCharts flips its axis when exporting data

I am facing an issue with the display of my Highchart in the web application. While it appears correctly in the browser, the exported chart flips the axis and shows a different image. Below are the options I have configured for my Highchart: var options = ...

Issue encountered while generating a package using npm init in Node.js

I am currently in the learning process of NodeJs from tutorialspoint(TP). Following instructions provided in this link, I tried to create a package by running the following command: C:\Program Files (x86)\nodejs>npm init This utility will w ...

Unable to exhibit missing data by utilizing conditional syntax within jsx

I've created a search system where users can input a place. If the place is found, it shows the details of the location; otherwise, it displays a "not found" message. Below is an excerpt of the code: code render() { var margin = { marginTop ...