Reputation: 1
Hello StackOverflow community,
I have problems adding names to THREE.Mesh() while batch loading them.
The code below is having the error:
function loadObjects () {
var objectURL = ["cube", "birdie", "sphere"];
for (var i = 0; i < objectURL.length; i++) {
loader.load(
"Ressources/models/" + objectURL[i] + ".json",
function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
var mesh = new THREE.Mesh(geometry, material);
mesh.name = String(objectURL[i]);
scene.add(mesh);
}
);
}
}
While loading a single is working fine:
function loadObject () {
var objectURL = ["cube", "birdie", "sphere"];
loader.load(
"Ressources/models/" + objectURL[1] + ".json",
function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
var mesh = new THREE.Mesh(geometry, material);
mesh.name = String(objectURL[1]);
scene.add(mesh);
}
);
}
All models are loaded and rendered correctly, but it is not possible to use scene.getObjectByName("birdie");
, when the objects are batch loaded.
About an answer I would be very happy. Regards Codepuree
EDIT: Found a way to batch load Objects:
var objectURL = ["cube", "birdie", "sphere"];
function loadObjects (iterator) {
var loadMesh = new THREE.Mesh();
loader.load(
"Ressources/models/" + String(vegetationURL[iterator]) + ".json",
function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
loadMesh = new THREE.Mesh(geometry, material);
loadMesh.name = String(vegetationURL[iterator]);
scene.add(loadMesh);
}
);
loader.onLoadComplete = function () {
iterator++;
if (iterator < objectURL.length) {
loadObjects(iterator);
}
}
}
loadObjects(0);
The problem was that the loader is loading asynchronously. So the load function is to slow for the for-loop. Loading it in a while loop causes and dead loop. That is why to go with the recursive way.
This works fine now and thanks for the help ther. :)
Upvotes: 0
Views: 77
Reputation: 888
Problem might be that when the lambda function is called the value of the i variable is objectURL.length, since the function can be called after the for loop is terminated.
Try this instead:
function loadObjects () {
var objectURL = ["cube", "birdie", "sphere"];
for (var currentURLId in objectURL){
loader.load(
"Ressources/models/" + objectURL[currentURLId] + ".json",
function (geometry, materials) {
var material = new THREE.MeshFaceMaterial(materials);
var mesh = new THREE.Mesh(geometry, material);
mesh.name = String(objectURL[currentURLId]);
scene.add(mesh);
}
);
}
}
Upvotes: 1