We can use two methods to remove the child of an Object3D
class object which is present inside the three.js scene graph:
The remove()
method
The removeFromParent()
method
remove()
methodThis method is invoked through the parent object.
parentObject.remove(childObject);
This method takes the Object3D to be removed as a parameter. Here,
parentObject
: This is the parent whose child we want to remove.childObject
: This is the child that we want to remove.Note: The
childObject
must already be a child ofparentObject
before it is removed. If it is not already a child, no effect takes place.
removeFromParent()
methodThis method is invoked through the child itself.
childObject.removeFromParent();
This method does not take any parameters.
childObject
: This is the child who is to be removed from its parent.
We'll demonstrate the removal of a child with the help of an example:
In the code shown above, we create a scene in three.js. Here, shape_one
is the square and is the parent of the two spheres. The green sphere is shape_two
and the red one is shape_three
.
Lines 47 & 48: We added shape_two
and shape_three
to shape_one
as children.
The scene graph of the code shown above looks something like the illustration shown below:
Removing a child from the parent object will make the scene graph look the following illustration:
This will prevent shape_two
from being rendered entirely as it is no longer a part of the scene.
Here,
Line 58: We remove shape_two
from the children of shape_one
using remove()
and can observe that it is no longer a part of the scene.
Line 61: We can uncomment this line and comment Line 58 to observe the same effect of removeFromParent()
method as well.