The amount of child elements in Three.js

After creating a three js object and adding some children to it, I changed the length of children to 0. As a result, the objects went out of screen. But will this action completely remove the objects from both the screen and memory?

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

To create children:

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);

The above steps were repeated for more spheres.

Then in the console, I entered:

balls.children = [];

This action removed all the spheres from the scene. But does this also erase all the sphere objects from the memory?

Answer №1

A common way to clear all elements in an array is by setting array.length = 0;. This action effectively deletes all elements within the array. Alternatively, if you set array.length = 2, only the first two elements will remain in the array while the rest are deleted. In Javascript, there is a built-in function known as slice() that also performs a similar operation.

Answer №2

To properly delete a child, it is recommended to first call remove(child) on the parent object, and then utilize dispose() for the child's material and geometry.

Here is an example 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);

// Perform certain actions

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

Remember to only dispose of the material/geometry if they are no longer being used by any other Mesh instances.

According to THREE.Object3D, in the method remove(object, ...):

"Removes the specified object as a child of this object. Multiple objects can be removed at once."

As per THREE.Geometry, in the function dispose():

"Ensure you call this method when disposing of a geometry to prevent memory leaks."

Similarly, from THREE.Material, in the method dispose():

"Use this to dispose of the material. Note that textures belonging to the material should be disposed separately using Texture."

If textures from textures are employed, make sure to dispose of them as well.

(Version: THREE.js r85).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Implement Clip Function with Gradient Effect in JavaScript on Canvas

Trying to incorporate the clip() function within the canvas element to create a unique effect, similar to the one shown in the image. I have successfully achieved a circular clip, but I am now aiming for a gradient effect as seen in the example. How can th ...

What is the most effective way to bring in "server-side only" code in Next.js?

I am currently working on my index page's getServerSideProps function and I want to utilize a function called foo, which is imported from another local file. This function relies on a specific Node library that cannot be executed in the browser becaus ...

Attempting to save MongoDB data into a variable for integration with Handlebars.js

Having an issue with storing MongoDB data in a variable to display in HTML using hbs. The specific error message is TypeError: Cannot read property 'collection' of undefined. Here's the code snippet I have written: const express = require(& ...

Unable to update the numerical value in the Material-UI version 5 TextField component

When attempting to display the decimal value 1.0 in the MUI5's TextField component, I encountered an issue. While I can change its value using the icons within the TextField, inputting any value directly seems to be ineffective. Additionally, backspac ...

Incorporating Redux into Angular 2 with SystemJS loading technique

I have been delving into learning Angular 2 and I am keen on integrating Redux into my project. Currently, I have set up my project using angular-cli on rc2 release. This is my systemjs configuration: /************************************************** ...

Exploring the Big O complexity of QuickSort in JavaScript

My experience with QuickSort involved testing two algorithms on LeetCode for a specific problem. Surprisingly, both algorithms worked, but one outperformed the other significantly, leaving me puzzled about the reason behind the speed difference. One of th ...

Creating a modal in Ruby on Rails with Bootstrap

I'm attempting to utilize bootstrap modal with ajax, but I'm facing an issue where the screen darkens upon clicking, but the modal never appears. Any tips or a better approach to tackle this problem? measures/index.html.erb <%= link_to &apo ...

Submitting a file to the Slack API via the files.upload method using jQuery

I'm attempting to upload a file on a webpage and send it to Slack using the Slack API. Initially, my code looked like this: var request = require('request'); $(".submit").click(function(){ request.post({ url: 'https://slack.co ...

Incorporating video.js into an Angular website application

I've encountered a strange issue while attempting to integrate video.js into my angular app. <video id="example_video_1" class="video-js vjs-default-skin" controls preload="none" width="300" height="264" poster="http://video-js.zenco ...

How to rotate an object in Threejs using the mouse without having to click and drag?

I'm searching for a solution to rotate around an object in Threejs without the need to hold down the mouse button. A good example can be found on this website: which utilizes Threejs. Despite searching through forums and documentation, I have been un ...

Display the entire HTML webpage along with the embedded PDF file within an iframe

I have been tasked with embedding a relatively small PDF file within an HTML page and printing the entire page, including the PDF file inside an iframe. Below is the structure of my HTML page: https://i.stack.imgur.com/1kJZn.png Here is the code I am usin ...

Ways to receive notification during the user's selection of an option by hovering over it

Is there a way to receive an event when a user hovers over a select option? I thought that using the onMouseOver or onDragOver props on the option component would work, but it seems like they only trigger for the parent select component. Below is a simpli ...

Incorporate additional form element functionalities using radio inputs

Recently, I created code that allows a user to duplicate form elements and add values by clicking on "add more". Everything is functioning properly except for the radio inputs. I am currently stuck on this issue. Does anyone have any suggestions on how I c ...

Divs in jQuery smoothly slide down when a category is chosen

As I work on a large website, I have hidden div tags in my HTML that I want to be displayed when a user selects a specific category. However, due to the size of the site, there are many hidden divs that need to be revealed based on different categories sel ...

Transforming button properties into a JSON format

I am currently in the process of developing a web application using node.js and mongodb. Within my app, there is a table that dynamically populates data from the database using a loop. I encountered an issue with a delete function that I implemented base ...

Learn how to easily upload multiple files from various upload points onto a single page using Node.js and express-fileupload

After searching on various platforms, including StackOverflow, I couldn't find a solution that fits my specific scenario. I've been struggling for hours to resolve this issue... In my handlebars page, there is an option for the user to upload fi ...

What is the best way to create a calendar that displays every day in a single row?

Is it possible to create a calendar with all days in one row? I've been searching for a solution to this problem without any luck. It's surprising that I haven't found a clear answer or explanation on how to achieve this. I'm sure man ...

What is the best method for deleting the 'records per page' label text from datatables?

I'm trying to customize my jQuery datatables by removing the label "Records per page." I already know that "oLanguage": { "sSearch": "" } can be used to remove the search label, but is there a similar option for hiding the results per page label? ...

Is it possible to render the v-for value dynamically?

I have a dynamic component and I'm trying to iterate through different objects from it. However, my current code isn't working as intended. Can someone please guide me on how to make the activeQuestion value in v-for dynamic? Thank you for your a ...

After a successful transactWrite operation using DynamoDB.DocumentClient, the ItemCollectionMetrics remains unpopulated

Currently, I am utilizing a transactWrite instruction to interact with DynamoDb and I am expecting to receive the ItemCollectionMetrics. Even though changes have been made on the DynamoDb tables, the returned object is empty with {}. Does anyone have any ...