How can I access scene.children elements in three JS?

I added some objects to the ThreeJS scene (using scene.add(object) ). I know the name of the object and just want to get its index from scene.children.

I tried using scene.children.indexOf("objectName") , but it returns a -1 index. Can anyone suggest what I can do?

thanks

+4
source share
4 answers
 var object = scene.getObjectByName( "objectName" ); 

or to recursively search for a scene graph

 var object = scene.getObjectByName( "objectName", true ); 

In addition, you can search by ID.

 var id = scene.getObjectById( 4, true ); 

three.js r.60

+7
source

You have the warning text as undefined because you are returning an object, not value/text . You will need to warn something like scene.getObjectByName( "objectName" ).name or scene.getObjectByName( "objectName" ).id , I believe.

0
source

I believe that something that can really answer your question is the following code that I use to clear the scene:

 while (scene.children.length > 0) { scene.remove(scene.children[scene.children.length - 1]); } 

Thus, I do not need to access the element by its name or identifier. The object is simply retrieved from the array with the index, so it likes scene.children[i] .

0
source

Relevant documents: getObjectById , getObjectByName . Important note from getObjectByName :

Note that for most objects, the name is the default empty string. You will have to install it manually in order to use this method.

This may be why you are getting undefined . Also, if you get undefined , try to access .name or .id for an error.

Another important point that I learned is that the value that getObjectById needs to getObjectById is object.id , not object.uuid . In addition, object.id is essentially just an object index in the children array.

Putting it all together:

 // var object = new THREE.Mesh(...) or similar object.name = 'objectName'; scene.add(object); var retrievedObject = scene.getObjectById(object.id); // or var retrievedObject = scene.getObjectByName('objectName'); alert(retrievedObject.name); 
0
source

Source: https://habr.com/ru/post/1498427/


All Articles