Having trouble incorporating Mesh instances into an array

I'm attempting to create multiple copies of a mesh randomly positioned throughout my THREE.Js scene. To achieve this, I have utilized the clone() method within a for loop. The console displays an array showcasing the clones I generated, however, when trying to access individual elements within the array, the console returns undefined to me. Here is the code snippet I implemented:

let ball = new THREE.Mesh();
loader.load('./ball.gltf', function ( gltf ) {
    gltf.scene.traverse(function(model) { //for gltf shadows!
        if (model.isMesh) {
          model.castShadow = true;
          model.material = sphereMaterial;
        }
    });
    ball = gltf.scene
    
    scene.add(ball);

    for (let i = 1; i <= 9; i++) {
        let newBall = ball.clone()
        scene.add(newBall)
        newBall.position.set(Math.floor(Math.random() * 20) * 2 - 10, Math.floor(Math.random() * 20) * 3 - 10, Math.floor(Math.random() * 20) * 2 - 10)
        pos_arr.push(newBall)
    }
    
}, undefined, function ( error ) {
    console.error( error );
} );

When I call console.log(pos_arr), this is what I see:

https://i.sstatic.net/Uc5bx.png

Subsequently, upon calling something like console.log(pos_arr[2]), all that's returned is undefined.

Is there anyone who might have insight into what could be causing this issue?

Answer №1

The primary reason for this issue is early access to the pos_arr. This means you are accessing it before the onLoad() function of the GLTFLoader has completed.

There are several approaches to resolving this issue, with the solution depending on the structure of your application. One recommended method is to pass a LoadingManager instance to all loaders and utilize its onLoad() callback to finalize scene setup or initiate object access.

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

Convert the numerical values from an array into an input field format

Currently, I have two inputs and an array with two number positions. The v-model in each input corresponds to a value in the array. Whenever a change is made in either input field, it reflects on the corresponding position in the array, which works perfect ...

Ways to organize extracted JavaScript information from objects based on a nested object attribute

I am attempting to arrange objects numerically in an array in ascending order, using a nested object property called 'score'. Here is the Array: [ {name:'dan', score:220}, {name:'lucy', score:876}, {name:'mike' ...

When accessing tagName in Internet Explorer 11, the name will be returned in uppercase with the namespace included. However, in Internet Explorer 7,

My goal is to extract all child elements within a DOM element with a specific tag name and store them in an array. <xs:menu> <xs:submenu> </xs:submenu> </xs:menu> var item=menu.children.tags("XS:SUBMENU") ; Internet Explorer 7 ...

How can I ensure a function only runs after all imports have been successfully loaded in Vue 3?

Encountering an issue with importing a large quantitative variable in Vue 3. Upon running onMounted, it seems that the import process is not yet complete, resulting in an error indicating that the variable tesvar is "uninitialized". The code snippet prov ...

Fragment shader parameters are no longer being transmitted in the basic shader evaluation

Some time back, I had the idea to experiment with a small three.js test that involved drawing a quad using 2 custom shaders. Taking some sample code and adding in the shaders resulted in a quick setup. However, since I'm embedding three.js directly fr ...

Angular RxJS: Trigger an action upon subscribing to or unsubscribing from an observable

I'm in the process of converting some Javascript events into Observables using RxJS within an Angular application built on the Ionic framework. My goal is to begin listening for events when the "client" invokes .subscribe(), and then stop listening wh ...

Click to save image using jQuery

I am trying to implement a feature where clicking on an image allows users to download it. I am using the download attribute for this purpose. <a href="http://mysite.ru/userfiles/certificate_2.png" class="download-certificate-link" data-title="certific ...

Harnessing the power of source material through a veil of shadows

How can I apply a material to create a stained glass effect in shadows? https://i.sstatic.net/uNMKu.jpg (source: 123rf.com) While I can currently project shadows, they appear as plain grey and do not match the source object's material. ...

How can I convert a Java array of arrays into JavaScript?

When working with Java, I need to create a JSON structure similar to this: [ [ timestamp , number ],[ timestamp , number ] ] This structure is necessary for displaying data on Highcharts graphs. I initially used a "LinkedList of LinkedList" format to ...

"How can I extract father's details by clicking on a button

After clicking, I need to access the parent element. Here is the HTML code I have: <button mat-icon-button (click)="download($event)"> The generated HTML code is as follows: <button _ngcontent-wsc-c153="" mat-icon-button=&q ...

Assign an identifier to the bootbox textarea

To initiate the bootbox with a textarea, use the following code snippet: bootbox.prompt({ title: "This is the title", inputType: 'textarea', placeholder: 'Feedback', callback: function (result) { console.log(result); } }); You ...

Only validate the nested object if the parent object is already present

In my scenario, I have a request body structured as follows: { "folder": { "value": "testFolder", "operator": "=" }, "name": { "value": "5456", "operator": "contains" } } While the presence of the request body is optional, I want to ensure that b ...

Adding error handling to my axios API calls for smoother error catching

Is there a way to modify the code below that displays posts from Reddit to show an error message if the HTTP request is incorrect or if the data cannot be retrieved? import React from 'react' import ReactDOM from 'react-dom' import &apo ...

Placement of watermark label above specific elements to prevent interference with click propagation

I have developed a unique watermark/hint feature for a dropdown menu by positioning a label directly over the select element. However, I am facing an issue where users are unable to open the drop down when clicking on the label as it seems to block the cl ...

JavaScript's concise ternary operation can be used for quick if/else statements when conducting

Here is my current if/else setup: async invoke(request, response) { const { deleted } = request.query; let users = []; if (deleted === 'true') { users = await User.findAndCountAll({ where: { ...

Combining various JSON objects by nesting them together

I'm in the process of creating an endpoint where I need to combine data from four different tables into one nested object. Each table record is retrieved in JSON format using sequelize - they include information on location, service, staff, and tenant ...

What is the reason behind limiting the yawObject position to a maximum of 10 in the Three.js PointerLockControls source code?

Currently, I'm engrossed in developing a fundamental Demo FPS engine, employing the PointerLockControls example from the Three.js source located here: https://github.com/mrdoob/three.js/blob/master/examples/js/controls/PointerLockControls.js /** * @ ...

What is the best way to send a JavaScript array to a Perl script using AJAX?

Is it possible to convert a JavaScript array passed via AJAX into a Perl array? Accessing in Perl: @searchType = $cgi->param('searchType'); print @searchType[0]; Result: employee,admin,users,accounts It appears that the first value in the ...

Issue with Three.js sample scene not functioning correctly

Forgive my lack of experience, but I am new to three.js and seeking guidance from the experts. I am starting with a basic scene to build my understanding from there. I began with an example scene from the documentation, but when I run it locally or on my s ...

Tips for adjusting jCountdown timer to be auto responsive while utilizing CSS sprite resources

The jCountdown plugin creates stunning effects that can be viewed at: After inspecting the resources, it appears that the plugin uses css sprite animation to achieve its effects. I am curious about how challenging it would be to make it responsive and avo ...