suhail c
suhail c

Reputation: 1199

Three js children length

I created a three js object and added some children to it. then i changed the length of children to 0. then the objects have gone out of screen. Will that make the objects fully removed from the screen and memory?

var balls = new THREE.Object3D();  // parent

for creating childrens

var geometry = new THREE.SphereGeometry(5, 32, 32);
var material = new THREE.MeshPhongMaterial({color: 0x0f0ff0, shininess: 50, transparent: true, opacity: 1});
var sphere = new THREE.Mesh(geometry, material);
sphere.position.x = scale('some random value');
sphere.position.y = scale('some random value');
balls.add(sphere);

above steps repeated for more spheres

then in the console i wrote

balls.children = [];

this removes all the spheres from the scene. Will that removes all the sphere objects from the memory also??

Upvotes: 1

Views: 1664

Answers (2)

Manuel Dipre
Manuel Dipre

Reputation: 483

The correct way for deleting a child is calling remove(child) from its parent, and then use dispose() on children's material and geometry.

In your code:

var balls = new THREE.Object3D();  // parent

var geometry = new THREE.SphereGeometry(5, 32, 32);
var material = new THREE.MeshPhongMaterial({color: 0x0f0ff0, shininess: 50, transparent: true, opacity: 1});
var sphere = new THREE.Mesh(geometry, material);
sphere.position.x = scale('some random value');
sphere.position.y = scale('some random value');
balls.add(sphere);

// Do some work

balls.remove(sphere);
geometry.dispose();
material.dispose();

Dispose the material/geometry only when it is not used by other Mesh anymore.

From THREE.Object3D at remove(object, ...):

"Removes object as child of this object. An arbitrary number of objects may be removed."

From THREE.Geometry at dispose():

"Don't forget to call this method when you remove a geometry because it can cause memory leaks."

From THREE.Material at dispose():

"This disposes the material. Textures of a material don't get disposed. These needs to be disposed by Texture."

If you use textures, you must dispose these too.

(THREE.js r85).

Upvotes: 1

Koushik Challa
Koushik Challa

Reputation: 11

Yes, when you have an array and then set array.length = 0; all the elements of the array will be deleted. When you type array.length = 2, all elements other than the first two elements will be deleted. Javascript has a function called slice() which does a similar thing.

Upvotes: 1

Related Questions