Loading Objects with Material Textures Ahead in Three.js

I am faced with the challenge of preloading multiple obj+mtl files using Three.js, each with distinct file paths, and I need to trigger another function once all the objects have finished loading.

Initially, I attempted to use a boolean variable that would change upon the successful loading of each obj file. However, my implementation didn't work as intended, ultimately causing the page to crash for unknown reasons.

All the file paths for the obj and mtl files are stored in an array for easy access.

You can view a snippet of my current approach here:

Despite my efforts, placing the load function within a for loop led to unexpected behavior.

Any assistance or insights you can provide would be greatly appreciated!

Answer №1

Utilizing the latest THREE.MTLLoader()
                    .setPath( 'models/obj/male02/' )
                    .load( 'male02_dds.mtl', function ( materials ) {

                        materials.preload();

                        Implementing the new THREE.OBJLoader()
                            .setMaterials( materials )
                            .setPath( 'models/obj/male02/' )
                            .load( 'male02.obj', function ( object ) {

                                Adjusting the position of the object to be at y = -95;
                                Adding the object to the scene.

                            }, onProgress, onError );

                    } );

OBJMTLLoader is no longer supported and has been replaced by using OBJLoader along with MTLLoader.

For a working example, check this link

Answer №2

To tackle this task, utilizing a three.js loading manager is essential. Here's how you can implement it:

Start by creating a manager:

var manager = new THREE.LoadingManager();
manager.onProgress = function ( item, loaded, total ) {
    // This function is triggered once an object has been loaded
};
manager.onLoad = function () {
    // All items have been loaded successfully
    // Proceed to call your other function
};

Next, create a loader using the manager and load the necessary items:

var OBJMTLLoader = new THREE.OBJMTLLoader( manager );

OBJMTLLoader.load(urlsOBJ[0], urlsMTL[0], function(object) {

    // Actions performed within your callback
    var newObject = object.clone();
    newObject.position.set(140, 10, 10);
    newObject.rotation.x = -99;
    scene.add(newObject);
    objectArray.push(newObject);

});

This code was tested on three.js r71.

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

Utilizing setState within the useEffect hook can lead to the application experiencing

Why does my code result in an endless loop error? This issue is pointing to the line marked with *: function Blog() { const [blog, setBlog] = useState({}); const query = useQuery(); async function fetchBlog(query) { const data = awai ...

Locate the div in the array that includes ValueA, and save ValueB from it into a new variable

When the button is clicked, I retrieve the current value of a Select control using the following code... $('#myBtn').on('click', function (clickEvent) { var nameSelected = document.getElementById('mySelectControl').getEle ...

The background image of my bootstrap carousel is not responsive to changes in the browser window size

Hey there, I'm new to the world of programming and currently working on a project to create the front end of my personal website. I've opted to utilize a bootstrap carousel background image slider in my index.html file. However, I've noticed ...

PHP - Retrieve fully rendered HTML content from an external page

I am a beginner when it comes to AJAX and PHP, and I have been experimenting with using a PHP HTML DOM Parser to retrieve the HTML from an external website. However, I have encountered an issue where the fetched HTML is only the content that was initially ...

Managing time in an Angular application using Typescript

I am facing an issue with formatting the time obtained from an API in my FormArray. The time is received in the format: 14.21.00 My goal is to convert this time to the following format: 2:21 PM I have attempted to format it using Angular's DatePip ...

Can we trust the accuracy of the official type definition for JSON.stringify?

Upon reviewing the official type definition for JSON.stringify, it appears that it states JSON.stringify always returns a string, even when passed undefined. interface JSON { stringify(value: any, /*...*/): undefined; } However, executing JSON.stringif ...

Troubleshooting issues with the Select List component in ReactJS

Having an issue with the select list as the onChange event is not triggering. Struggling to set the selected value from the list in the this.state variable. Any assistance on this matter would be greatly appreciated. class SelectActivity extends React.C ...

Selenium throws an error message stating 'NoSuchAlertError: no alert is currently opened'

When using Selenium, I encounter an issue where clicking a button triggers an alert box, but accepting the alert box results in an error message. element.click(); driver.switchTo().alert().accept(); The problem is quite unpredictable. ...

"Troubleshooting Problem with JSON Encoding in PHP and Parsing with getJSON in

Apologies if this sounds like yet another discussion on the topic, but I've been struggling for hours without finding a solution. I'm attempting to retrieve data from a MySQL database, generate a JSON using PHP, and then parse this JSON in JavaS ...

How come defining the state using setTimeout does not display the accurate properties of a child component?

Presented here is a component designed to render a list of items and include an input for filtering. If no items are present or if the items are still loading, a message should be displayed. import { useState } from "react"; export const List = ...

Incorporating jQuery to Load Content into a DIV while preserving the original JavaScript

I am attempting to implement the following <script> $(document).ready( function() { var data = 'testing' $("#about").on("click", function() { $("#main-content").load("/about.html"); ...

Leveraging JQuery for form submission

My webpage contains a form with the following structure: <form action="/" method="post"> <select id="SelectedMonth" name="SelectedMonth"> <option>7/1/2017</option> <option>6/1/2017</option> </select> </form> ...

Having trouble with my ASP.Net OnClick Subs not functioning as desired

I have implemented onClick handlers to process button clicks that query SQL. The issue I am facing is that these queries sometimes take between 10 to 30 seconds to return a response. To prevent click-stacking during this time, I disabled the buttons. Howev ...

Are you experiencing issues with the .submit() function when used in conjunction with other

Currently, I am working on a survey form that incorporates JQuery to dynamically display or hide fields based on user selections. //FORM CONDITIONALS: This script is responsible for hiding all the helpfulness radios and only displaying them when "Yes" fo ...

Issue: The value of an object is not defined (evaluating '$scope.inputcode.password')

HTML Form: <form ng-submit="mylogin()"> <div class="list"> <label class="item item-input"> <span class="input-label">Username</span> <input type="text" ng-model="inputcode.username"> ...

Creating interactive tables in HTML and Javascript where users can expand and collapse rows by clicking on a parent row

After days of trying to solve a specific issue, I have realized that I cannot do it without some help. The task at hand is to enable the functionality of clicking on a table row to reveal more details, but in my case, these additional details are presented ...

Issue with setState not being triggered within axios POST request error handling block

I am in the process of setting up an error handler for a React Component called SignupForm.js, which is responsible for handling user registrations. Specifically, I am working on implementing a handler to deal with cases where a user tries to sign up with ...

Occurrences repeating several times following the incorporation of fresh content into the DOM

I am facing an issue with my plugin. I have implemented an update method to handle new elements added to the DOM. Initially, everything works perfectly without any errors or issues. However, when a new element (div with class "box") is added to the DOM, th ...

Tips for aligning an element in the center in relation to its sibling above

Help Needed with Centering Form Button https://i.sstatic.net/QhWqi.png I am struggling to center the "Send" button below the textarea in the form shown in the image. Despite trying various methods like using position absolute, relative, and custom margin ...

Using Angular 8.x for routing with customized outlet names

I am attempting to set up routing in my Angular 8.x application, utilizing lazy loading and named outlets. Here is the current configuration: main-layout.html <header> <app-top-menu></app-top-menu> </header> <mat-sidenav-cont ...