How to sequentially load multiple obj files in Three.js

Currently, I am utilizing the obj/mtl loader from three.js to import various obj files along with mtl files. The challenge I am facing now is the need to load multiple objs one by one. Even though I have implemented THREE.DefaultLoadingManager.onProgress to incorporate a "Loading Screen", I'm unsure of how to monitor loaded === total within the loop for adding new objs. Should I consider using a recursive function instead?

I appreciate any assistance you can provide. Thank you.

Answer №1

In order to enhance the loading process of objects in a three-dimensional environment, a callback function is utilized to trigger the subsequent loading steps seamlessly.

let currentIndex = 0;
const filesToLoad = ['file1.obj', 'file2.obj'];

const objectLoader = new THREE.OBJLoader();

function loadNextObject() {

  if (currentIndex >= filesToLoad.length) return;

  objectLoader.load(filesToLoad[currentIndex], function(loadedObject) {

    scene.add(loadedObject);

    currentIndex++;
    loadNextObject();

  });

}

loadNextObject();

To further advance the functionality, the code must be expanded to include loading materials for the objects.

Answer №2

I found some inspiration in @brakebein's answer which led me to figure out the solution myself. Here is the full code that worked for me, in case it helps anyone else - KUDOS TO BRAKEBEIN! :)

// Loading Texture and OBJ files
let OBJfiles = ['love3','rose'];
let _MTLLoader = new THREE.MTLLoader().setPath( 'models/' );

// This function loads the next MTL and OBJ file in the queue
function loadNextMTL () {

    if (index > OBJfiles.length - 1) return;

    _MTLLoader.load( OBJfiles[index]+'.mtl', function ( materials ) {
        materials.preload();
        new THREE.OBJLoader()
            .setMaterials( materials )
            .setPath( 'models/' )
            .load( OBJfiles[index]+'.obj', function ( group ) {
                mesh = group.children[0];
                mesh.material.side = THREE.DoubleSide;
                mesh.position.y = 0.25;
                mesh.scale.set(0.02,0.02,0.02);
                markerRoot[index].add(mesh);

                index++; // Increment count and load the next OBJ
                loadNextMTL();

            });
            // onProgress, onError > These can be used to keep track of the loads
        });

}

loadNextMTL (); // Start the preloading routine

Answer №3

Instead of manually trying, you can utilize THREE.DefaultLoadingManager.onLoad to check.
This method should efficiently handle the job for you.

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

Can the execution of setTimeout() impact the overall performance?

Is it possible that this code will cause the client to slow down due to the extended timeout? //and let's revisit this after some time setTimeout(function() { updateWeather(lat,lng); }, 60000); ...

Changing color in JQuery based on class and the content of HTML elements

I am attempting to utilize jQuery to extract the inner html of a div with the class name "box_bottom". These divs are dynamically generated by JavaScript, fetching data from XML. As a result, there could be multiple occurrences based on the XML, and I nee ...

Tips for enhancing the functionality of components within Vue

My expertise lies primarily in React, and I'm now exploring the Vue-centric approach to achieve the following: I want to enhance this component: , so that the label-position is set to top on mobile devices and left on desktop. However, I'm not s ...

Dragging elements with jQueryUI multiple times

Is there a way to configure drag and drop functionality so that one element can be dragged multiple times? I attempted to create something similar to this http://jsfiddle.net/28SMv/3/, but after dragging an item from red to blue, the element loses its abi ...

Experiencing Issues with AngularJS: Encountering Undefined Object while Passing Parameters via ui-sref

Hello, I am completely new to angularjs and wanted to share my code snippet: HTML <table ng-table="tctrl.tableEdit" class="table table-striped table-vmiddle" show-filter="true"> <tr ng-repeat="w in $data" ng-class="{ 'active': w.$ed ...

Is it correct to use React Router's useNavigate with a useEffect hook for navigation?

I am a beginner to React and I have been working on creating a loading/greeting page that automatically navigates to the next page after a few seconds. In React Router v6, there is a useful hook called useNavigate() which allows you to control navigation. ...

The URL in React Router updates as expected, but when attempting to render a component using a button component link

I have encountered a situation similar to the one portrayed in this CodeSandBox example, where I am required to implement react routing within two distinct components. The issue that is perplexing me is that, when I navigate down to either the Profile or ...

Retrieving the class name using jQuery

In my HTML code, there is a div with three classes defined as: <div class = "a b c"> .. </div> My goal is to access only the class b using the .attr() method. Is this achievable? ...

Assemblage of Marionettes: Adding multiple elements to the DOM

I am working on a Marionette application and have come across an issue with inserting new tab items. I have a collection of tabs, but when adding a new item, I need to insert DOM elements in two different areas. The problem is that Marionette.CollectionV ...

Leverage and repurpose OOP objects

I am exploring how to inherit from Button using prototypes. Despite my efforts, the alerted name remains "Sarah" as it is the last Child created. I believe the Creator Class should be responsible for setting the name using a Method in Button. Check out m ...

C# web service is unable to return a specific value

I attempted to use a basic web service (just to test if the value will populate in the JavaScript code). I experimented with a very simple snippet, but it kept returning 'undefined'. Can you offer some guidance? I have tried several solutions wit ...

Middleware for enabling the Cross-Origin Resource Sharing (CORS) functionality to efficiently manage preflight

My CORS configuration is set up globally to handle credentials like this: app.use(cors({ origin: 'https://example.com', credentials: true })) However, there are certain routes where I need to allow OPTIONS requests. Following the documentation, ...

Dynamically loading iframes with JQuery

I have implemented a jQuery script to load another URL after a successful AJAX request. $(document).ready(function() { var $loaded = $("#siteloader").data('loaded'); if($loaded == false){ $("#siteloader").load(function (){ ...

Displaying genuine HTML content in a React application using Algolia Instantsearch

After setting up a demo app using React with an Algolia search feature, I uploaded some indices into Algolia. The content consists of raw HTML. Is there a way to display this content as real HTML using Algolia? ...

What is the recommended library for managing a task queue in this project?

Is there a library or package available for Node.js that can help me create a task queue with a fixed timeout between the start of each task and an overall callback that is triggered after all tasks have finished? https://i.stack.imgur.com/j1wCY.jpg ...

Is there a way to rotate the custom marker icon in vue2-google-map?

After reading the documentation, I discovered that using path is the only way to rotate the marker. In an attempt to customize my marker, I created my own PNG image. However, I have been unsuccessful in overriding the CSS of the marker. I even tried to ov ...

Non-responsive Click Event on Dynamically Created Div Class

I am facing some uncertainty in approaching this problem. In the HTML, I have created buttons with additional data attributes. These buttons are assigned a class name of roleBtn. When clicked, they trigger the jQuery function called roleBtnClicked, which ...

How can I showcase the selected file using jQuery's querySelector?

I have successfully implemented a file upload feature using jQuery querySelector. Now, I am looking for a way to display the selected file name in a span element after the user selects the file. Here is my HTML code: <span id="filename"></span&g ...

Obtaining an element through its id using an expression in an Angular directive

Here's a complex question that needs to be broken down. I'm trying to mimic the behavior of the native <label> for <input>. Since nesting is not an option, I use a style like this: <input type="checkbox" id="test" /> Some other ...

Having issues with socket.io connectivity on my Node server

I am setting up my node server to update all connected clients with real-time information. However, when I run the code provided below, the io.sockets.on('connection') callback keeps firing constantly, flooding the console with the message Client ...