Trouble with Three.js: Issue with loading textures by name

I have a file with a .obj extension that I am currently loading using a loader. This file contains multiple meshes which I want to use separately as individual objects. The challenge I am facing is that each of these objects has a distinct texture. However, when I attempt to load them, the same texture gets loaded twice. I suspect this issue might be related more to JavaScript than three.js itself. Any insights or assistance on this matter would be greatly appreciated!

Below is the code snippet I am currently working with:

    for (var i = 0; i < object.children.length; i++)
    {
        var child = object.children[i]
        child.scale.set(15, 15, 15)
        child.position.y += 0.01
        console.log('Loading texture for: ' + child.name)
        textureLoader.load('assets/' + child.name + '.png', function(image)
        {
            console.log('Searching for: ' + child.name)
            var texture = new THREE.Texture()
            texture.image = image
            texture.needsUpdate = true
            child.material.map = texture
            console.log('Texture loaded for ' + child.name)
        })
    }
    scene.add(object)

The issue I am encountering is that only the first object from the list is being loaded correctly. Even though the for loop is executing four times with different children, the console log in the textureLoader.load callback is showing the name of the first element twice.

Answer №1

It seems like writing this may not yield the desired result: console.log('Looking for: ' + child.name) since the variable 'child' is defined outside of the function(image), which means its value could potentially change before console.log is executed. For more information on variable scopes in JavaScript callback functions, refer to this link.

This explains why you repeatedly get the same name printed, but it doesn't clarify why you're only getting two printouts instead of four. Ideally, you should be getting four printouts.

If you're only seeing two console.log() outputs, it's likely that only two .png files were loaded successfully. Ensure that all four files exist or check if there are possibly two texture files shared among the four shapes.

If the issue persists, kindly provide the exact printouts you're receiving.

Update 1: Give the following code a try and let me know the output:

console.log('Loading texture for: ' + object.children[0].name);
textureLoader.load('assets/' + object.children[0].name + '.png', function(image) {
        console.log('Loaded texture for ' + object.children[0].name);
});
console.log('Loading texture for: ' + object.children[1].name);
textureLoader.load('assets/' + object.children[1].name + '.png', function(image) {
        console.log('Loaded texture for ' + object.children[1].name);
});
console.log('Loading texture for: ' + object.children[2].name);
textureLoader.load('assets/' + object.children[2].name + '.png', function(image) {
        console.log('Loaded texture for ' + object.children[2].name);
});
console.log('Loading texture for: ' + object.children[3].name);
textureLoader.load('assets/' + object.children[3].name + '.png', function(image) {
        console.log('Loaded texture for ' + object.children[3].name);
});

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

Discovering the process of mapping transitions in MUI

I'm struggling with mapping my products in mui and placing each one in Grow. However, I keep getting this error message: "Warning: Failed prop type: Invalid prop children of type array supplied to ForwardRef(Grow), expect a single ReactElement". Can a ...

Finding the final day of a specific year using the moment library

When it comes to determining the last day of a year, hard-coding the date as December 31st seems like a simple solution. While there are various methods using date, js, and jquery, I am tasked with working on an Angular project which requires me to use mom ...

Creating unique div IDs dynamically in PHP, JavaScript, and MySQL

I'm currently working with an ajax code that fetches data from table columns when a specific data is selected from the dropdown menu. In my surveycontent.php file, I have the following script: <script type="text/javascript"> function show ...

What is the best way to move the numerical range value into a span element?

How can I implement the "update" function to retrieve the current slider value and transfer it to a Meter element with the message "Value: [current value]". The indicator color should be #ffff00 if the current value is at least 85, otherwise, it should b ...

Unable to navigate a simulated scrollbar

As someone who is new to web development, I am embarking on the journey of building a UI Grid that can effectively display a large amount of data. My goal is to implement a scrollbar that allows for horizontal scrolling across approximately 1,000,000 data ...

Updating a database seamlessly via a dropdown menu without having to refresh the entire webpage

Before we proceed, please take a look at the following code: $(document).ready(function() { $("#alternatecolor [type=button]").each(function() { $(this).on('click', function() { btnObj = $(this); rowId = $(this).attr("rowId") ...

Performing aggregation in MongoDB with nested subdocuments

I have a specific document structure as shown below: { "_id": "some_uuid", "inv": { "food01": "id01", "food02": "id02", "food03": "id03" }, " ...

Keep the user on the current page even after submitting the parameter

I have a situation where I am loading a page into a specific div. This loaded page contains a link that includes a parameter which directs to another page for deletion. However, when I click on the loaded page within the div, it redirects me to the deletio ...

Why isn't any of my AngularJS code running as expected?

I've recently started learning AngularJS, but I'm encountering an issue where none of my code is being executed when I run the page. Instead, all I see on the website is {{angular-message}} and I'm receiving the error "Error: [ng:areq] Argum ...

When an Ajax call is made, my .html page transforms into a .php page using jQuery

The Issue While using my PHP function to send emails, everything goes smoothly. However, I'm facing an issue where I don't want the page to refresh, so I've implemented AJAX in the code below: reservation.html <form class="form-horizon ...

Tips for handling a JSON payload retrieved through a POST request

I'm currently working on a button that triggers a POST call to retrieve a json response from the server. My goal is to display this json response in a new (chrome) browser tab. Here's what I have so far using Angular: $http.post(url, data) .t ...

Issues Concerning Shadows in THREE JS

Currently, I have an animation set up for a "flag" where the cloth material flaps in the wind and folds onto itself. My goal is for the flag to display shadows on itself as it moves. Take a look at this fiddle to visually see what I mean: https://jsfiddle ...

Why doesn't the z-index of child elements function properly when their fixed parents share the same z-index value?

I have utilized jsfiddle to replicate my problem. My goal is to position .top .inside above .bottom .inside. I am aware that z-index only functions within its respective position type, for example fixed and absolute do not share the same z-index level. How ...

What is the best way to implement an onReady promise in a JavaScript application?

Exploring some Advanced topics in JS I am currently diving into and there is an interesting concept that's piqued my curiosity. I've been developing a VueJS application and now I'm looking to expose certain data and even methods from Vue ou ...

using angular.js to assign a value to an <input> field

There seems to be an issue with the code, as I am unable to see the value in the HTML: '<div ng-app="BusinessinfoModule" ng-controller="BusinessinfoController" <label>Your Business Name</label> <input ...

What is the best way to include a form within every row of an HTML datatables structure?

I have a regular table that is populated with data fetched via Ajax, and it appears like this: Ajax <script> $(document).ready(function() { $('#mytable').DataTable( { "ajax": "myurl", "dataType": 'json', ...

Sending a parameter from a click event to a function

Struggling with a jQuery and AJAX issue all night. I am new to both and trying to implement something similar to this example. I have an edit button with the ID stored in a data-ID attribute. Here's an example of what my button looks like: <butto ...

Tips for concealing the ID value within a URL or parameter

I just started learning Angular JS and I have a question about hiding parameters in the URL when clicking on anchor tags to send data to another controller. I don't want any ID or its value to be visible in the URL. Is it possible to hide parameters i ...

Retrieve text from a dropdown menu while excluding any numerical values with the help of jQuery

I am currently implementing a Bootstrap dropdown menu along with jQuery to update the default <span class="selected">All</span> with the text of the selected item by the user. However, my objective is to display only the text of the selected it ...

Is it possible to convert a string of elements in JavaScript into JSON format?

Within my JavaScript code, a variable holds the following information: url=http://localhost quality=100 tag="4.4, 5.5" I am interested in converting this data to JSON format using JavaScript, like this: "result": { "url": "http://localhost", "qu ...