Converting Three.js objects into arrays

I am new to Three.js and I want to add my 'palmtree' object to an array. I believe my code is correct, but something seems off.

Here is the snippet of my code:

var objects = [];
var mtlLoader = new THREE.MTLLoader();
mtlLoader.load("objects/palmtree.mtl", function(materials) {
    materials.preload();
    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.load("objects/palmtree.obj", function(palmtree) {
        palmtree.position.x = 205.12577753354344;
        palmtree.position.y = 2;
        palmtree.position.z = -600.0613083252872;
        palmtree.scale.x = 64;
        palmtree.scale.y = 64;
        palmtree.scale.z = 64;
        scene.add(palmtree);
        objects.push(palmtree);
    });
});

After adding the palmtree object to the scene, I noticed that when I check objects.length, it returns 0. I'm not sure what I'm doing wrong.

If you have any suggestions on how to properly push the palmtree object to the objects array, please let me know. Thank you!

Answer №1

It seems like there is a fundamental concept missing here. Object loading happens asynchronously, so if you try to access objects.length outside of the callback function, it will likely be 0 because your palm tree has not finished loading yet.

Instead, try checking the length of objects inside the callback function like this:

var mtlLoader = new THREE.MTLLoader();
mtlLoader.load("objects/palmtree.mtl", function(materials) {
    materials.preload();
    var objLoader = new THREE.OBJLoader();
    objLoader.setMaterials(materials);
    objLoader.load("objects/palmtree.obj", function(palmtree) {
        palmtree.position.x = 205.12577753354344;
        palmtree.position.y = 2;
        palmtree.position.z = -600.0613083252872;
        palmtree.scale.x = 64;
        palmtree.scale.y = 64;
        palmtree.scale.z = 64;
        scene.add(palmtree);
        objects.push( palmtree );
        console.log(objects.length); // <-- will output new length
    });
});

With this approach, the output will be 1.

Therefore, the array length will only show 1 once the loading process is complete and the callback function has been executed.

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

Real-time monitoring within a callback function in Angular 5

I need to ensure that a specific callback is executed only after receiving a response, starting from the line this.groupDefaultExpanded = -1; onwards. loadLoginDetails() { this.derivativeSpecService.getDerivativeDetails().subscribe( res => ...

retrieve the information from a specific field within the store and store it in an array

Perhaps this is a question that pertains to using pure JavaScript, but for some reason I can't seem to figure it out. I am currently working on extjs4.2 using Sencha Architect and have received a JSON response from the server in the following format: ...

When attempting to showcase array information in React, there seems to be an issue with the output

After printing console.log(response.data), the following output is displayed in the console. https://i.sstatic.net/LLmDG.png A hook was created as follows: const [result,setResult] = useState([]); The API output was then assigned to the hook with: setRe ...

Divide the array of words into segments based on the maximum character limit

I am looking for a way to divide an array of words into chunks based on a maximum number of characters: const maxChar = 50 const arrOfWords =['Emma','Woodhouse,','handsome,','clever,','and','rich,&apo ...

What is the process for applying a class in jQuery to empty HTML elements?

Working on a WordPress/PHP website and looking to dynamically add a class when child elements are empty? This is the HTML structure: <div class="featured-block"> <a href="/" class="featured-block__item cf"> <div class="featured-bl ...

Discover how to retrieve the calculated percentage within CSS with the assistance of jQuery specifically designed for Webkit

I'm currently working on a simple sliding animation. However, the div that slides in is utilizing percentages for its width and right positioning. The issue arises specifically in Webkit browsers. When using jQuery to retrieve the value, it returns t ...

Module-alias cannot be resolved by esm

Currently, I am utilizing the combination of esm package and module-alias. However, it appears that esm is not recognizing module-alias's paths. This is how I am loading my server file: nodemon -r esm ./src/index.js 8081 At the beginning of my inde ...

JavaScript code to activate a text box when a checkbox is clicked

I have a dynamic table that is generated by JavaScript based on the selected item from a dropdown list. The table consists of a column for checkboxes, a column for displaying names, and a column for inputting quantities. I would like to have all textboxes ...

Parsing JSON Arrays in Swift results in a value of zero

JSON data output {"inputs":{"latitude":"29.93","longitude":"-95.61","capacity":"30.30","azimuth":"180","tilt":"40","array_type":"1","module_type":"1","losses":"10"},"errors":[],"warnings":[],"version":"1.0.1","ssc_info":{"version":45,"build":"Linux 64 bit ...

JS/Apps Script: Passing object and its keys as function parameters

When working with Google Apps Script, I have a specific task that involves looping through data and writing only certain keys to a sheet. I want this looping operation to be done in a separate function rather than directly in the main function, as it will ...

Enhancing Browser Experience: The correct method for dynamically adding an AngularJS controller through a Chrome Extension's Content

Currently, I am in the process of developing a Chrome extension using AngularJS. To attach a controller to the required DOM elements on a webpage, I have been utilizing the following content script code: setController() { if(this.setContollerConditio ...

Develop interactive web applications using Typescript

Having difficulty compiling and executing the project correctly in the browser. The "master" branch works fine, but I'm currently working on the "develop" branch. It's a basic web project with one HTML file loading one TS/JS file that includes i ...

Array volatility - ensuring memory coherence of the elements

Consider this code snippet: class A { private Map<String, Object> taskMap = new HashMap<>(); private volatile Object[] tasksArray; // assume this occurs on thread1 public void assignTasks() { synchronized(taskMap){ ...

Accessing index.html via file:// from Vue-cli template

Whenever I execute the npm run build command using this Vue-cli template, it displays this message: Hint: The built files are designed to be served over an HTTP server. Attempting to open index.html via file:// will not function correctly. Therefore, the ...

Is there a way for me to obtain the present value of the chosen button in the list below?

I am working with a group of three buttons labeled English, Hindi, and Urdu. How can I retrieve the value of the selected button in a JavaScript function? <div class="btn-group" data-toggle="buttons"> <label class="btn btn-primary active"> ...

Generate JSON dynamically using a foreach loop

I am utilizing the jquery flot charts library to visualize my data. Take a look at this example JSFiddle I created demonstrating how the JSON structure required for the chart should be. The data I am working with is sourced from a MySql stored procedure a ...

Angular parent scope does not reflect changes when a directive updates the shared scope variable

My directive is designed to validate and modify a specific binded value before triggering the button action. However, I am facing an issue where any updates made to the directive value are not being reflected in the parent scope. Even though I have used (= ...

Is it possible to assign variables inside an http call from a function in AngularJS?

Seeking urgent assistance. I need help with a function that resembles the following: $scope.getData = function(id) { $http.get('/url' + id).success(function (data) { return data.a.b.c; }); }; In another function, I have the fol ...

Developing a Vue.js application with a universal variable

In the previous version of Vue.js, 0.12, passing a variable from the root component to its children was as simple as using inherit: true on any component that needed access to the parent's data. However, in Vue.js 1.0, the inherit: true feature was r ...

What is the best way to use jQuery to retrieve information from one child element in an XML API in order to locate another child

Hi there, I'm new to jQuery and could use some help. I'm attempting to retrieve specific information like CPU and RAM details from a particular phone model. I've written the jQuery code, but I'm having trouble displaying the RAM and CPU ...