I can add a cube to the scene with this code:
scene.add(cube1)
and remove it:
scene.remove(cube1)
But the doubt is… there is any property of scene
object which checks if cube1 is into the scene or not?
I can add a cube to the scene with this code:
scene.add(cube1)
and remove it:
scene.remove(cube1)
But the doubt is… there is any property of scene
object which checks if cube1 is into the scene or not?
There are three ways to achieve this :
Option 1: Check using scene.children
const isInScene = scene.children.includes(cube1);
console.log(isInScene); // true if cube1 is in the scene
Option 2: Use scene.getObjectById()
Every object in Three.js has a unique id
. You can use this to check:
const isInScene = scene.getObjectById(cube1.id) !== undefined;
console.log(isInScene); // true if cube1 is in the scene
Option 3: Use scene.getObjectByName()
If you have given your object a name
, you can check for it:
cube1.name = "MyCube";
const isInScene = scene.getObjectByName("MyCube") !== undefined;
console.log(isInScene); // true if cube1 is in the scene
If you’re working with many objects, it might be useful to use unique names
or keep a separate record of objects you’ve added to the scene for easier management. However, the scene.children.includes()
method is generally sufficient for simple use cases.
I tried to add with this only when them load:
for(i1 in players){
if(!players[i1].cube){
players[i1].cube=new THREE.Mesh(box2,green_material)
}
if(!scene.children.includes(players[i1].cube)){
scene.add(players[i1].cube)
}
console.log(scene.children.includes(players[i1].cube))
players[i1].cube.position.set(players[i1].x,calcSurface(players[i1].x,players[i1].z)+3,players[i1].z)
}
But the scene show at this form:
EDIT:
Another times its appears as this:
EDIT 2:
I suspect that this bug is the supression of this fragment of code:
for(i1 in players){
try{
scene.remove(players[i1].cube)
}catch(e){
console.warn(e.message)
}
}
EDIT3:
Now it shows this weird bug:
EDIT4:The result:
box2=new THREE.BoxGeometry(1,2,1)
green_material=new THREE.MeshLambertMaterial({color: "rgb(0,255,0)" })
update=()=>{
requestAnimationFrame(update)
for(i1 in players){
if(!players[i1].cube){
players[i1].cube=new THREE.Mesh(box2,green_material)
}
if(scene.children.includes(players[i1].cube)){
players[i1].cube.position.set(players[i1].x,calcSurface(players[i1].x,players[i1].z)+3,players[i1].z)
}else{
scene.add(players[i1].cube)
}
}