Using a loop to incorporate numerous objects in three.js - inserting both .obj and .mtl files in bulk

I've encountered an issue in my code where I'm unable to locate the mistake(s)... The problem lies within a loop that loads multiple objects and assigns them names, but the "objects" array remains empty as a result. My goal is to give each object a unique name for intersection detection purposes (which works fine in the code). However, when interacting with different parts of a loaded object (a cathedral), the database is being contacted even though all objects have the same name. Can anyone shed light on why this might be happening? Here is the code snippet: The 'objects' array stores all geometries, and 'object' is the argument of the function. 'load_obj' is defined by a loop using the values stored in another array named OBJETS containing the names of different parts of the cathedral.

for (var i in OBJETS){   
    load_obj = OBJETS[i];
    loader.load('./Donnees/OBJ/'+load_obj+'.obj', './Donnees/OBJ/'+load_obj+'.mtl', function ( object ) { 
        object.name = load_obj;         
        scene.add(object);      
        objects.push(object);     
    }, onProgress, onError );       
}

Appreciate any assistance provided!

Answer №1

In this scenario, the key factor at play is that javascript operates as an asynchronous language.

Essentially, the load function is triggered asynchronously, allowing the for loop to continue its execution before it concludes. As a result, when the for loop halts, the variable load_obj retains the value of the last object.

This resource offers a solution to tackle this issue.

for (var i in OBJETS){ 
    (function(index){
        load_obj = OBJETS[index];
        loader.load( './Donnees/OBJ/' + load_obj + '.obj', './Donnees/OBJ/' + load_obj + '.mtl', function ( object ) { 
            object.name=load_obj;         
            scene.add( object );      
            objects.push(object);     
        }, onProgress, onError ); 
    })(i);
}

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

What is the best way to solve the problem of Chrome auto-complete overlapping with labels in Vuetify?

When attempting to make a login form using outlined text fields in Vutify, there is an issue with Chrome autocomplete overlapping the labels. <v-text-field v-model="email" label="e-mail" name="email" outlined prep ...

Identifying mouseover event across numerous elements in JavaScript

I'm attempting to identify the mouseover event on multiple elements using their class as a reference. For instance: <div class="myElement">1</div> <div class="myElement">2</div> <div class="myElement">3</div> & ...

Guide on how to incorporate a Wistia Channel video gallery into a Gridsome webpage/template

I'm currently working on a Gridsome website and I'd like to incorporate a Wistia Channel video gallery into one of the pages. Specifically, I want to place it within the "frame" div class on top of the existing image. However, I'm unsure abo ...

Developing a search feature using Ajax in the MVC 6 framework

Embarking on a new project, I have chosen c# .net 6 MVC in VS2022... In my previous projects, this code has run flawlessly. @section Scripts { <script type="text/javascript"> $("#Klijent_Name").autocomplete({ ...

Tips for accessing the firebase user's getIdToken method in Next.js after a page reload

Currently, I am developing a Next.js project and implementing user authentication using Firebase's signInWithPhoneNumber method for phone number verification. After successful verification, I receive a Firebase user with the getIdToken method to retri ...

Use vue.js to add a block of content after every sixth iteration in a loop

Currently, I have a list of offer cards rendering through a loop. I am adding a row div every 3rd column (bootstrap) element. Now, I need to also add another column element (banner block) for every 6th element in order to achieve a layout like the one show ...

How can you access the children of a PHP array using parameters?

I have a situation that is quite unique where I am dealing with an array structured like the following: $a = array('a' => array('b' => array('c' => 'woohoo!'))); My goal is to access specific values within ...

Guide to utilizing various functions, with equations, within a specific scope in angularJS

myApp.controller('incomeController', ['$scope', function($scope) { $scope.pay = 0; $scope.hours = 0; $scope.tax=0.19297; $scope.total = function() { return $scope.pay * $scope.hours;} $scope.taxTotal ...

Do JavaScript functions operate synchronously or asynchronously?

Here is the JS code snippet I am working with: <script> first(); second(); </script> I need to ensure that second() will only be executed after first() has completed its execution. Is this the default behavior or do I need to make any modific ...

Is there a way to incorporate an SSL certificate into a JavaScript POST request?

I need to send a post request to an endpoint using a SSL certificate in either typescript or javascript. This is for a project that I am currently working on with Ionic 3. ...

How can I access a nested document using Mongoose?

Suppose I have a data collection structured like this: [ { "_id": "637cbf94b4741277c3b53c6c", "text": "outter", "username": "test1", "address": [ { " ...

Calculation mode within an array (multiple modes present)

I am currently facing an issue with calculating the Mode (most frequent number in an array) in Swift. Here is an example of the code: func mostFrequent(array: [Int]) -> (value: Int, count: Int)? { var counts = [Int: Int]() array.forEach { coun ...

The material of the imported glTF model in Three.js has an unexpected 'format' field

Upon loading a textureless model from a glTF file using GLTFLoader, I found that the object's material includes a mysterious "format" field. Surprisingly, simply making changes to the material does not work properly unless this field is removed. For ...

Error encountered: Unable to locate class during unmarshalling process. Issue arises when attempting to unparcel a Parcelable

I am encountering an issue with a Parcelable Class. My objective is to transfer an image as a ByteArray between activities and eventually to a remote webservice. The error message I am facing is java.lang.ClassNotFoundException: ... Class not found when u ...

Create a standard chart with a colored map using Three.js

Recently, I dove into the world of Three.js and found myself on a mission to convert a color map into a normal map. My goal is to create a normal map similar to [image 2], based on the color map shown in [image 1]. Instead of simply uploading files, I wa ...

What is the reason behind jQuery(this).css('background-image') returning the browser's URL?

There are three divs in the code snippet below. <div id="div#product_img_wrapper"> <div id="product_design1" class="timage" style="z-index: 20; background-image: url('');"></div> <div id="product_design2" class="tim ...

Navigating through the various iterations of jQuery

Unique Case Study I'm currently facing a dilemma involving the integration of jstree and jquery-ui datepicker. The scenario is this: I am attempting to utilize jquery-ui-datepicker on an input element that is dynamically inserted into the DOM after ...

Using the npm timepicker in Laravel 5.8 with precision and efficiency

Looking for some guidance here as a newcomer to installing packages in Laravel. I'm currently working on implementing the timepicker feature from . In order to do this, I've already executed the command npm i jquery-timepicker. However, I seem t ...

Is it possible for two distinct devices to generate the same HWID using Pushwoosh Cordova API?

Our app relies on HWIDs generated by Pushwoosh to distinguish between devices. After reviewing traffic logs, I noticed a peculiar pattern of what appears to be the same device sending HTTP requests from various ISPs within short time intervals. It seems t ...

Methods for Unwinding ARRAY_AGGs in a Snowflake Query

My challenge involves performing a SELECT on multiple joined VARIANT columned tables. The main record is retrieved as DATA, while all supporting information surrounding it is obtained from supporting joined tables and returned as INCLUDED. To address this ...