Three.js getObjectByName: How to Find a Specific Mesh
Finding specific 3D objects within a complex Three.js scene can be
challenging. This article provides a quick guide on how to assign a
unique name to a mesh and retrieve it efficiently using the
getObjectByName method, complete with a practical code
example.
In Three.js, every object that inherits from
Object3D—including meshes, groups, lights, and cameras—has
a name property. By assigning a string to this property,
you can easily query the scene graph to find and manipulate that
specific object later.
Step 1: Assign a Name to Your Mesh
When creating your mesh, assign a unique string to its
name property:
const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cubeMesh = new THREE.Mesh(geometry, material);
// Assign a unique name
cubeMesh.name = "my-unique-cube";
scene.add(cubeMesh);Step 2: Retrieve the Mesh using getObjectByName
To find the mesh later, call the getObjectByName method
on the parent object, which is typically your scene. The
method performs a recursive depth-first search through the scene’s
children.
// Retrieve the mesh by its name
const retrievedMesh = scene.getObjectByName("my-unique-cube");
if (retrievedMesh) {
// Manipulate the retrieved mesh (e.g., change its color or position)
retrievedMesh.material.color.setHex(0xff0000);
retrievedMesh.position.y = 2;
} else {
console.warn("Mesh not found in the scene.");
}Key Considerations
- Recursive Search:
getObjectByNamesearches the object it is called on and all of its descendants. For better performance in complex scenes, you can call it on a specificGroupor parent container rather than the entiresceneif you know where the mesh resides. - Uniqueness: Three.js does not enforce unique names.
If multiple objects share the same name,
getObjectByNamewill return the first match it encounters. Ensure your names are unique to avoid targeting the wrong object. - Undefined Results: If no matching object is found,
the method returns
undefined. Always implement a check before attempting to manipulate the returned object to prevent runtime errors.