What is the best way to prioritize loading JSON models first in three.js and declare a variable before initializing?

I am looking to efficiently load multiple JSON models and store them in global variables for easy access. This will streamline tasks like copying, translating, and more without the need to reload a model each time.

After trying various methods, I have noticed that the loading of these models occurs asynchronously.

It seems that the models are being loaded after all other processes have completed. Consequently, when I try to access the variables, they remain empty or do not function as expected. Is there a way to prioritize loading the models first, waiting for completion, and then proceeding with the rest of my code including functions like init()?

For example:

var loader = new THREE.JSONLoader();
// Global object variables
var test1 = new THREE.Object3D();
var test2 = new THREE.Object3D();
// More Object3D declarations follow

loadParts();
init();
animate();

function init() {
    // Clone object
    var newPart = test1.clone();
    console.log("new part ID: " + newPart.id);
    // Additional functionalities...
}

function loadParts() {
    // Load different models using the Three.js loader
}

function createPart(geometry, materials, object3Dtemp) {
    // Create a new three.js Mesh object
}

function placePart(object3Dtemp, x, y, z) {
    // Place a cloned object at specific coordinates
}

In the console, you may see output similar to:

New part ID: 12
THREE.WebGLRenderer framework initialized 
Model parts created: 21, 22, 23, and so on...

Answer №1

JSONLoader.load() function is designed to work asynchronously, meaning that when it is executed, the code will continue to run without waiting for the loader to complete its task.

Take a look at this specific line of code:

 loader.load( "Models/test1.js", function ( geometry, materials ) { createPart( geometry, materials, cover ) } );

In this line, the callback function "function(geometry, materials){...}" will be triggered once the .load operation finishes. In this example, the user-defined function "createPart" is utilized within the callback. To ensure each model loads sequentially, you can invoke the next model's loader within the previous model's "createPart" function. Once the last model's "createPart" has completed, you can then call the init() function.

If your models are numbered consecutively, you might be able to automate this process using a pseudo-for loop with chained callbacks. Otherwise, manual intervention may be necessary.

var partNo = 0;
var partCount = 5;
loadUp(partNo);

function loadUp(_partNo){
    var loader = new THREE.JSONLoader();
    loader.load("Models/part"+_partNo+".js", function(geo, mat) {
        createPart(geo, mat, ..., _partNo);
    }
}

function createPart(geo, mat, ...,  _partNo) {
    //create mesh etc as before
    ...

    if(_partNo + 1 < partCount){ //for first 4 parts
        _partNo++;
        loadUp(_partNo); //load next part
    }
    else { //this is the 5th part indicating completion
        init();
    }
}

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

Encountering an "Unexpected token '{'" error while attempting to import chart.js is likely due to the import call expecting only one argument

I'm currently working on a node.js app that utilizes chart.js for visualizations. However, I'm running into errors when trying to import and use Chart. To serve chart.js to the client, I used npm to install it and then added the following code: ...

Creating a Float32Array with an equal number of points for varying geometries in Three.js

I am faced with a task where I need to load various models in different formats (.obj, etc.) and generate particles based on their geometry positions using Float23Array's. As each model has unique geometries, the number of particles varies depending ...

Tips for showcasing all values in a nested array

In my Vue application, I am dealing with a nested array where users can select one date and multiple times which are saved as one object. The challenge I am facing now is how to display the selected date as a header (which works fine) and then list all the ...

Dynamic field refreshed on server side upon second button press

I'm encountering an issue where a hidden field that I update via Javascript only reflects the new value after clicking a button twice. Surprisingly, I can view the updated hidden field value when inspecting it through the browser. Default.aspx <s ...

react validation for dropdown, react-datepicker, and hour input at intermittent intervals

I have integrated the following packages into my project :- react-datepicker library for selecting from time and to time date validation with date-fns, moment.js, additional validations using jQuery and lodash libraries/packages If you want to view my pr ...

utilizing the json format for communication between an Android application and a servlet

Is it possible to transfer data in JSON format from an Android client to a servlet? If yes, what are the benefits of using JSON for this purpose? ...

What is the proper way to indicate the pointer to the current element within the array?

How can I modify a code that displays a list of posts? import React from "react"; type respX = { "id": any, "userId": any, "title": any, "body": any, } interface PropsI { } interface StateI { data: respX []; } export class Compone ...

Unwrapping JSON body into a list of MyClass objects in Apache Camel

Could someone please help me with unmarshalling a JSON string body to a List of MyClass? The code snippets provided below are not functioning properly. from("direct:testroute") .log("Received body ${body}") .unmarshal().json(JsonLibrary.Jackson, List.clas ...

Generating live data for JSON schema values

As a beginner in working with json schema, I am facing difficulty finding a solution to my current problem. I want to populate the data sent by the server to a json editor using the provided schema. Note: The following is just a snippet of the schema. The ...

Error in Displaying Vuetify Child Router View

I am currently working on integrating a child router-view to be displayed alongside surrounding components. Here is an overview of my routing setup: { path: "/login", name: "TheLoginView", component: TheLoginView, }, { path: "/dashboa ...

I am experiencing an issue with Array.some not functioning properly within my React component, whereas Array.map is working

I am attempting to utilize Array.prototype.some() within my React component to check if a particular value exists in my array of objects. However, I keep encountering the error message data.some(...) is not a function. Interestingly, Array.prototype.map() ...

Tips for displaying HTML content using an array in Vue JS

Hi, I'm a beginner with Vue JS and I'm working on passing an HTML table using this array. I have a dropdown where I can select the option I want, but I'm struggling to figure out how to include HTML within it. Whenever I try, it ends up disp ...

When using React, appending a React Link tag to an existing list item may result in the addition of two objects instead of the desired

Trying to create a loop that checks if an object's date matches with a date on a calendar. If it does, I want to add a React Link tag to the respective li element. The loop logic works well, but the issue is when appending the Link tag using createTex ...

Button halts the playback of numerous audio tracks simultaneously

I'm in the process of creating a Launchpad, where each row consists of 8 buttons/audio tracks and a stop button. My goal is for each stop button to halt all audio playing on that specific row when pressed—for instance, pressing Stop Button 1 would c ...

How can you modify Jquery show_hide so that the page automatically scrolls to the bottom of the concealed field when the button is clicked?

On my website, there is a button that reveals a map when clicked. The button is visible when the page loads, but once clicked, the map slides open and goes out of sight since the page loads at the top as usual. My goal is to have the page automatically scr ...

Creating an Editor for Input Text Field in HTML: A Step-by-Step Guide

In the vast landscape of JS libraries that can achieve this function, like Trumbowyg and more. However, prior to my rails project displaying that slim version, I need to ensure JavaScript is properly escaped! Therefore, I need to create an editor using o ...

Adjusting the URL variable based on the selected checkbox option

My mobile website offers users the option of a bright or dark interface using a checkbox styled like an iPhone IOS7 switch. The functionality is working as expected, but I'm now facing an issue with passing the status of the checkbox between pages. I ...

Unable to retrieve data from JSON file using Ajax request

Trying to populate an HTML table with data from an external JSON file is proving to be a challenge. Despite making an AJAX request using pure JavaScript, nothing happens when the "Test" button is clicked. Take a look at the JSON data: { "row":[ { ...

The Google reCaptcha reply was "Uncaught (in promise) null"

When using reCaptcha v2, I encountered an issue in the developer console showing Uncaught (in promise) null message regardless of moving the .reset() function. Here is the console output: https://i.stack.imgur.com/l24dC.png This is my code for reCaptcha ...

Divide a JSON API object into segments within an express application

One way I'd like to organize my API's output is by splitting it into multiple pages. My idea is to access them using URLs like this: http://127.0.0.1:3000/api/articles/0/<API-TOKEN> This specific URL would display the first page containing ...