假设您有一盏灯,并且在某个时候将其删除,然后您想再次添加它。
您在渲染函数中添加和删除,这些函数不断被动画函数调用。
你检查一个复选框是否被选中,你添加(scene.add(light),否则删除(scene.remove(light)。
那么,在这种情况下,我们在渲染功能中勾选复选框时是否添加了很多对象(灯光),对性能有什么影响吗?我们可以添加一个标志或计数器来不继续添加,但是我们还可以做些什么,比如检查 isInstanceof 吗?
我发现对于 canvas/threejs 渲染器的服务器端控制,您可以将这些对象存储在一个数组中,如果您使用加载器或其他网格,您可以为其添加一个名称。
这将更容易(在我的情况下)检查对象是否已经在场景中。
例子:
var AllObject = []; // <-- the array that holds all objects in the scene.
var scene = new THREE.Scene(), // <-- creates basic threejs scene
camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ),
renderer = new THREE.WebGLRenderer(); //<-- creates WebGL renderer
renderer.setSize( window.innerWidth, window.innerHeight ); //<-- set the size of the canvas
document.body.appendChild( renderer.domElement ); //<-- add canvas to body
/* now the part that i use to check if an object is already in scene. */
var geometry = new THREE.BoxGeometry( 1, 1, 1 );
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
AllObject[NAMEOFOBJECT] = new THREE.Mesh( geometry, material ); //<-- here comes the trick, insted of making a new var object just put it into an array with [] not {}!
scene.add( cube );
现在,如果您在下面使用这些 if 语句,您可以找到您的对象,并且 if 语句将检查数组的indexOf
位置编号。
if(~AllObjects.indexOf("NAMEOFOBJECT"){
// you could remove the object by using scene.reomve(AllObjects.NAMEOFOBJECT);
// or just say for example console.log("Object already in the scene");
}else{
// here you can make the object if it doesn't exists.
}
NAMEOFOBJECT
可以是任何你想要的名字。