在批量加载时向THREE.Mesh()添加名称时出现问题

时间:2015-08-12 14:13:51

标签: javascript three.js

Hello StackOverflow社区,

在批量加载时,我在向THREE.Mesh()添加名称时遇到问题。

以下代码出现错误:

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);
            }
        );
    }
}

加载单个工作正常:

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);
        }
    );
}

所有模型都已正确加载和渲染,但是当批量加载对象时,无法使用scene.getObjectByName("birdie");

关于答案,我会非常高兴。 关心Codepuree

编辑: 找到了一种批量加载对象的方法:

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);

问题是加载程序是异步加载的。因此,对于for循环,加载函数会变慢。在while循环中加载导致死循环。这就是采用递归方式的原因。

现在工作正常,感谢帮助。 :)

1 个答案:

答案 0 :(得分:1)

问题可能是当调用lambda函数时,i变量的值是objectURL.length,因为在for循环终止后可以调用该函数。

请改为尝试:

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);
            }
        );
    }
}