如何加载一次模型并将其存储到变量中?

How to load a model once and store it to a variable?

我在加载这样的模型时遇到问题:

var Beech;
var loader = new THREE.JSONLoader();
loader.load( "./models/trees/Beech/Beech.json", function( geometry, materials ) {
Beech = addMorphTree(geometry,materials,0.5); });

并像这样使用它:

function addMorphTree(geometry,material,scale){
            mat=new THREE.MeshFaceMaterial( material );
            mat.side=THREE.DoubleSide;
            Tree = new THREE.Mesh( geometry,mat);
            Tree.scale.set(scale,scale,scale);
            //Tree.position.set(x,y,z);
            Tree.rotation.x = Math.PI/2;

            //scene.add( Tree );
        return Tree;}

我的问题是如何使用此变量创建模型的副本而不是每次都加载它?当我尝试使用

scene.add(Beech);

在加载程序之外,模型不会显示。我见过其他类似的问题,但所有的答案都是在加载程序中使用 scene.add 的地方。

我认为当您尝试在加载器外部添加模型时模型没有出现在场景中的原因是加载是异步完成的。这意味着,当加载程序正在加载时,其余代码将 运行。所以如果你尝试在加载函数之后直接在场景中添加"Beech",它还没有加载完成。

var Beech;
var loader = new THREE.JSONLoader();
loader.load( "./models/trees/Beech/Beech.json", function( geometry, materials ) {
Beech = addMorphTree(geometry,materials,0.5); });
scene.add(Beech);  // <-- this will run before the function above is finished,
                   //thereby adding a undefined variable to the scene.

如果你想要一个以上的变量实例,也许你可以试试 clone() 函数。由于Beech是一个Mesh对象,而Mesh继承自Object3D,所以也可以使用Object3D的成员函数

var Beech;
var loader = new THREE.JSONLoader();
loader.load( "./models/trees/Beech/Beech.json", function( geometry, materials ) {
Beech = addMorphTree(geometry,materials,0.5); 
for(var i=0;i<5;i++){
  scene.add(Beech.clone()) //creates 5 trees
}
});