Reputation: 1598
I have a .obj file that I'm using a loader to load. Inside the object file, I have a bunch of meshes that I want to use individually, kind of like a file that contains everything. However, each "object" has a separate texture. When I try to load it, it tries loading the same texture twice. I have a feeling this is more of a gotcha with JavaScript than three.js. Any help is greatly appreciated!
Here is my current code:
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('Looking for: ' + child.name)
var texture = new THREE.Texture()
texture.image = image
texture.needsUpdate = true
child.material.map = texture
console.log('Loaded texture for ' + child.name)
})
}
scene.add(object)
What ends up happening is only the first object in the list ends up loading. I have verified that the for loop runs 4 times, and each child is different. However, when logging to the console in the callback for textureLoader.load, the name shows up as the first element twice
Upvotes: 0
Views: 133
Reputation: 1778
I don't think you can write this: console.log('Looking for: ' + child.name) Because child is defined outside of function(image) and its value may change by the time console.log is called. See this: scope of variables in JavaScript callback functions
So the above explains why you get repeated printout of same name. But it doesn't explain why you get only two printout. You should get 4 printouts.
If you only get two console.log() outputs then that means that only two .png files were loaded successfully. So make sure all 4 files exists or see if there are actually 2 texture files that are being shared among 4 shapes.
If the problem continues gives us the exact printouts that you get.
Update 1: Try this and tell me what output you get?
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);
});
Upvotes: 1