The proper method for clearing out all items from the environment

Although there are numerous questions on SO that address the topic of removing everything from a scene, none of the methods I've tried seem to work as expected. There isn't a definitive solution provided in the documentation either, so I'm hoping someone can point me in the right direction.

Here is the current function I'm using to clear the scene of all objects:

function removeAll() {
    while (scene.children.length > 0) {
        scene.remove(scene.children[0]);
        if (scene.children[0] == THREE.Mesh || scene.children[0] == THREE.Object3D || scene.children[0] == THREE.Group) {
            scene.children[0].dispose();
            scene.children[0].geometry.dispose();
            scene.children[0].material.dispose();
        }
    }
}

While this method appears to visually remove everything from the scene, my issue arises when I call this function followed by the function that creates a new scene or reloads the existing one. More objects appear in the scene after calling the creation function (init()), which I confirmed using renderer.info in the console.

I've also observed that each time I use the removeAll() function and then refresh the scene, the performance decreases gradually, likely due to improper removal of objects.

Therefore, my question is this:

What is the correct way to completely clear out everything from the scene?

To provide some context:

I have an HTML menu where users can select which scene they want to transition to. It's crucial for me to eliminate all existing objects before loading the elements specific to the chosen scene. While I have successfully implemented this feature, the only hiccup lies in properly removing the preceding objects before introducing the new ones.

Answer №1

In my analysis, the crucial point to address is that only disposing of the top level scene children leaves potential issues with objects that have further child elements. Proper disposal may not be occurring in these cases.

To ensure thorough cleanup, the most effective approach would involve disposing of the renderer entirely, creating a new one, discarding the scene, and allowing for garbage collection.

If you prefer to attempt a methodical removal process, it will be necessary to recursively navigate through the children and dispose of any geometries, materials, and textures they possess.

An extensive dispose function can be found in this linked post. One adjustment I recommend making involves modifying diposeHierarchy to detach objects from each other as follows:

function disposeHierarchy (node, callback)
{
    for (var i = node.children.length - 1; i >= 0; i--)
    {
        var child = node.children[i];
        disposeHierarchy (child, callback);
        callback (child);
        node.remove(child);
    }
}

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

Animate a box moving continuously from the right to the left using jQuery

I'm trying to create a continuous motion where a box moves right, then left, and repeats the cycle. However, I can only get it to complete one cycle. $(document).ready(function() { function moveBox() { $('#foo').css({ 'ri ...

Searching in real-time with ajax in CodeIgniter framework is a seamless and efficient process

I'm a beginner in CodeIgniter and eager to learn. Currently, I'm facing an issue where the data is not being populated on the search page. In the model: function fetch_data($query) { $this->db->select('*'); $this-> ...

Exploring layered data through specific properties

Imagine a scenario where I have an array filled with data. Each element in this array is an object that could contain: an id some additional data a property (let's name it sub) which may hold an array of objects with the same properties (including t ...

Display webpage content in an Iframe using Javascript after PHP code has been executed

Despite researching keywords like PHP // Javascript // Load // URL online, I'm still struggling to fully grasp the concepts. Real-life case studies have been helpful, but I must admit that I'm feeling a bit overwhelmed at the moment. I created a ...

Open $_POST in a new tab that has been edited for your convenience

<form method="post" target="_blank" action="battle.php" onsubmit="window.open('battle.php','','width=700,height=500,toolbar=0,menubar=0,location=0,status=0,scrollbars=0,resizable=0,left=30,top=0');" > < ...

Attempting to create a login and registration form

Hello, I am attempting to create a form that can generate new user accounts and passwords. These values should be stored from the input tag when the user clicks on the register button. Unfortunately, I am encountering an issue where clicking the register ...

The ConsoleCapture does not capture every console error for Sentry

Running into an issue capturing console errors with Sentry in a Next.js app. The problem arises from an error within a library that is inaccessible to us, specifically related to WebSocket "WebSocket is already in CLOSING or CLOSED state" This error is c ...

What is the best way to eliminate the left padding on a TimelineItem component?

When using the Timeline component to display information, there are three columns: TimelinItem, TimelineSeparator, and TimelineContent. I tried setting the padding of TimelineItem to 0 but it didn't work. The <Trace/> component is a sub-compone ...

Create a THREE.Shape that imitates the functionality of context.clip()

With THREE.Shape, I have the ability to create holes within shapes. However, instead of creating holes, I am looking to establish a clip mask. I specifically want to confine the rendering of the shape within a mask, akin to HTML's canvas/context .cli ...

Using JavaScript to locate and emphasize specific words within a text, whether they are scattered or adjacent

I need help finding a JavaScript code for searching words in a text using a form and a search button. I found one that works for multiple words in a row, but it doesn't work if the words are mixed up. What changes should be made to fix this issue? An ...

Discover the method to retrieve the chosen value from a list of radio buttons using AngularJS

After making an AJAX request and receiving JSON data, I have created a list of radio buttons with values from the response. Although I have successfully bound the values to the list, I am facing difficulty in retrieving the selected value. Below is a snipp ...

Leverage the power of Web Components in Vue applications

Currently, I am attempting to reuse Web Components within a Vue Component. These Web Components utilize the template element for formatting output. However, when I insert them into the Vue Template, they are either removed from the DOM or compiled by Vue. ...

Tips for automatically updating the time in a React application while utilizing the 'date-fns' library

I've been working on my personal Portfolio using React and I'm looking to add a feature on the landing page that showcases my local time and timezone to potential recruiters. However, there's a small hiccup in my implementation. The displaye ...

Checking if the upload process has been completed using XMLHttpRequest Level 2

Currently, I am utilizing ajax for uploading files. Once the file has been uploaded, PHP needs to conduct a thorough check on it (including mime type, size, virus scan using clamscan, and more). This process can take a few seconds, especially for larger fi ...

Mishandling of string interpretation

I'm having trouble converting ANSI color codes from console output into HTML. While I discovered a script that can handle this task, I am struggling to make it parse the strings within node js properly. Even when I attempted to JSON.stringify it to in ...

What causes AJAX to sometimes output with incorrect encoding?

After receiving a file from a server using AJAX (Angular), the file, a simple XLSX document, is sent as shown below: ob_start(); $file = \PHPExcel_IOFactory::createWriter($xls, 'Excel2007'); $file->save('php://output'); $respon ...

Create a Vue application that is built on modules which could potentially be absent

I am currently developing a Vue+Vite app with module-based architecture. I have several Vue components and some parts of the app are functioning correctly. However, I want to ensure that the missing components are not imported or used in the application. H ...

Steps for implementing a dynamic animation within a table cell when the value is updated

Incorporating vuetify and nuxt into my web application, how can I implement an animation on a cell when its value changes? I attempted to attach a reference to my table element like so: <v-data-table ref="table" :items="data" :hea ...

What steps should I take to create a plugin for a library if defining it as a peerDependency does not provide a specific implementation for me to work with?

Requirements for My Plugin: I'm currently in the process of developing a new plugin that is dependent on popularLibrary.js. Here are the key points about my plugin: It will not function properly if popularLibrary.js is missing. It is designed to wo ...

Steps for converting an HTML form into a sophisticated JavaScript object

Is it possible to transform a form into a complex JavaScript object based on a structured form layout? I am not sure if there is a better way to accomplish this, but essentially what I am looking for is the following scenario: <form> <input n ...