I attempt to use the OBJECT3D array

As a beginner with Three.js, I am trying to add my 'model' object to an array. I believe my code is correct.
I have declared my variable as nextobj = [ ];.

function Loadobj() {
    var mx = [-1500,1500] , my = [350,350] , mz = [-1000,-1000];
    var nextobj = []; //Keeping Array Model

    for(var i = 0; i < 2; i++) { 
        var mtloader = new THREE.MTLLoader(); 
        mtloader.load('obj1/az-mp0076.mtl', function (materials) {
        materials.preload(); 
        var objloader = new THREE.OBJLoader();
        objloader.setMaterials( materials );
        objloader.load('obj1/az-mp0076.obj', function (object){ 
            model = object;
            model.position.set(mx[i],my[i],mz[i]);
            scen.add(model); 
            nextobj.push(model); 
            console.log(nextobj.length);  //Checking data in Object
            });
        });
    }
}

Step 1:
When I loop through 1 Object, it's displayed

https://i.sstatic.net/3ktGD.jpg

Step 2
When I loop through more than 1 object, it is not displayed, but my data is complete.

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

How can I add my objects to the array? Thank you.
I am unsure of what might be wrong in my code.

Answer №1

Try implementing a recursive function when running the Loadobj method or transform it into a promise. In the for loop, there are two callbacks for loading materials and objects. The issue arises from the loop executing without waiting for each callback to complete loading, resulting in synchronous execution. However, the methods for loading materials/objects are asynchronous, with results only available inside the callback functions. To ensure fully loaded objects, manipulate the results of loading methods only after the callbacks have finished loading each item and then call Loadobj again once the previous execution is done.
Using a recursive function:

var mx = [-1500,1500], my = [350,350], mz = [-1000,-1000];
var nextobj = []; //Keep Array Model
var numOfObjs = 1;
var start = 0;
function Loadobj() {
  if (Loadobj == numOfObjs) return;
  start++;
  var mtloader = new THREE.MTLLoader(); 
  mtloader.load('obj1/az-mp0076.mtl', function (materials) {
    materials.preload(); 
    var objloader = new THREE.OBJLoader();
    objloader.setMaterials(materials);
    objloader.load('obj1/az-mp0076.obj', function (object) { 
      model = object;
      model.position.set(mx[start],my[start],mz[start]);
      scen.add(model); 
      nextobj.push(model);
      console.log(nextobj.length);
      Loadobj();
    });
  });
}

Another approach involves using Promises:

function Loadobj(obj) {
  return loadMaterials()
    .then(function(materials) {
      return loadObjs(materials, obj);
    })
    .catch(function(err) {
      console.log(err);
   });
}

function loadMaterials() {
  return new Promise(function(resolve, reject) {
    var mtloader = new THREE.MTLLoader(); 
    mtloader.load('obj1/az-mp0076.mtl', function(materials) {
      materials.preload(); 
      resolve(materials);
    });
  });  
}

function loadObjs(materials, obj) {
  return new Promise(function (resolve, reject) {
    var objloader = new THREE.OBJLoader();
    objloader.setMaterials(materials);
    objloader.load('obj1/az-mp0076.obj', function(object){ 
      var model = object;
      model.position.set(obj.mx, obj.my, obj.mz);
      // scene is available globally
      scene.add(model); 
      nextobj.push(model);
      resolve(model);
    });
  });
}

var objs = [
  {
    mx: -1500, 
    my: 350, 
    mz: -1000
  },
  {
    mx: 1500, 
    my: 350, 
    mz: -1000
  }
];

var nextobj = []; 

// use reduce to iterate over objs
objs.reduce(function(acc, obj) {
  return Loadobj(obj);
}, Promise.resolve());

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

My API is feeding data to the Material UI CardMedia image

Has anyone encountered a similar error while using the CardMedia API provided by Material-UI? I am currently utilizing the Card & CardMedia components from material-ui to display data fetched from an api. However, I am facing difficulty in displaying ...

Ensuring the absence of values in deconstructed variables within an object

In my quest to efficiently destructure the end_time property from the this.props.auction object, I encountered the code snippet below. const {auction: {auction: {end_time}}} = this.props; The problem with this code is that the constant will be undefined ...

"Enhancing Efficiency with Tagging and Contextual Autocomplete

I have integrated into my project for tagging and autocompletion features. Currently, I am able to autocomplete a single term successfully: This is the console log: GET .../source.php?term=value01 This is the Javascript code snippet: $("#input-newsear ...

The Importance of Strict Contextual Escaping in ReactJS

When making an API call, we receive a URL in the response. In Angular JS, we can ensure the safety of this URL by using $sce.trustAsResourceUrl. Is there an equivalent function to trustAsResourceUrl in React JS? In Angular, //Assuming 'response&apos ...

Tips for resolving the error message "TypeError: Cannot access property 'category' of undefined" while working in a React environment

Hey there, I encountered an issue while trying to destructure in react and can't figure out why the title is appearing as an error message. Below is the code snippet: const {correct_answer, incorrect_answers} = data[0] const arr = [correct_answer, ... ...

Submitting quiz responses through a PHP based form

I am currently facing an issue with integrating forms and a quiz on my website. Individually, both work fine but when combined, they do not function as expected. Specifically, the quiz itself operates correctly, however, it fails to send the results via P ...

Error: Call stack limit reached while passing JSON data using Node.js

I am utilizing the ajax-request module to send Json data using a post request in my Node.js application. Below is the relevant code snippet: logMessage : function(url, message, next) { var d1 = message["sender"]; var d2 = { id: message[sender"]["id"], ...

Video from Brightcove continues to play even after closing the modal dialog

My concept for opening a Brightcove video in a modal dialog when a button is clicked has been successfully implemented. Below is the code snippet I used for this implementation: Html code: <a class="videoTutorialB" href="#">Watc ...

utilizing an ajax request to clear the contents of the div

When I click on Link1 Button, I want to use ajax to empty the contents in the products_list div <button type="w3-button">Link1</button> I need help with creating an ajax call that will clear the products in the product_list when the link1 but ...

Customize your Google Translate experience by choosing your own option values

Is there a way to trigger the same JavaScript calls by clicking on an option value in an HTML select element as with text-based links in the Google Translate widget? Check out this jsfiddle for more information <html> <body> <select i ...

Obtain the form value upon submission without the need to reload the page

I am facing an issue where I have a form and I want to trigger the display of a div (in the same page) and execute a JavaScript function upon clicking submit, all without causing a page refresh. <form action="#" method="post" name= "form1" id = "form ...

Toggling markers according to form selections is not functioning

My goal is to dynamically show or hide markers on my Google Map that represent houses and condos, based on the features selected by the user from a select box with id #features. For example, if a user picks 'Swimming Pool' as a feature and click ...

Using Mongoose with Next.js to implement CRUD operations

I have been successful in implementing POST and GET methods in my Next.js app using mongoose, but I am facing challenges with the delete operation. This is an example of my POST method located in the API folder: export default async function addUser(req, ...

Tips for correctly linking JS and CSS resources in Node.js/Express

I have a JavaScript file and a stylesheet that I am trying to link in order to use a cipher website that I created. Here is my File Path: website/ (contains app.js/html files and package json) website/public/css (contains CSS files) website/public/scri ...

When I utilize axios to send the request, the express routes for creating a new JSON entry in the mongo collection function correctly

Currently, I am working on building a course registration system that utilizes a form to send student data to a database. I have successfully created Express routes to add new entries to a mongo collection through a post request. Everything functions as ex ...

Internet Explorer does not return results when using AJAX during the onchange event (specifically for IE only

My code is functioning correctly on other browsers, however in IE it does not provide any result when I select the dropdown button. Instead, it changes and displays an empty result. This is my AJAX: $("#book").change(function(){ var DOMBULK = $(" ...

Shader of the sea on a unique gltf model

I'm trying to apply an ocean shader to my 3D model by combining the "shaders/ocean" and "loader/gltf" example scenes. I want to see the ocean shader on my custom 3D model, but my knowledge is limited. Apologies for that. const waterMat = new THREE.Mes ...

The $scope in Angular doesn't seem to be working as expected in the callback function, despite using $scope

I'm currently working on converting the JSFiddle found here to AngularJS: http://jsfiddle.net/danlec/nNesx/ Here is my attempt in JSFiddle: http://jsfiddle.net/leighboone/U3pVM/11279/ var onAuthorize = function () { updateLoggedIn(); $scope. ...

Purging a Collection

I have a pretty straightforward setup using Wordpress Advanced Custom Fields. I want to enhance my custom posts by adding additional fields and displaying them on the post page. The current code I have works well, but when it comes to a custom field with m ...

Email the jQuery variable to a recipient

I'm facing an issue with sending a jQuery variable containing HTML and form values via email using a separate PHP file with the @mail function. My attempt involves using the jQuery $.ajax function on form submit to send this variable, but unfortunate ...