Clear the area of any and all items

I attempted to create a function that would remove all objects from the scene at once, but it only removes one object each time it is called.

GeometryModel.prototype.clearScene = function(scene) {
var i;
for(i=0; i < scene.children.length; i++){
     obj = scene.children[i];
     scene.remove(obj);
  }
}

Another approach I experimented with and found successful is:

scene.children={};

However, I am uncertain if this method is correct.

Answer №1

To achieve the desired outcome, you must take the opposite approach:

for( var i = scene.children.length - 1; i >= 0; i--) { 
     obj = scene.children[i];
     scene.remove(obj); 
}

This is necessary because with each iteration, the .children array is modified as items are removed, causing the indexing of the array to change.

If you wish to gain a better understanding, try unraveling the for loop and observing how the index within the array evolves.

Answer №2

To achieve this, you can use a while loop:

while (item.children.length)
{
    item.removeChild(item.children[0]);
}

Explanation:

The condition object.children.length will be true as long as there are elements in the object's children. By removing the first child each iteration, you ensure that all children are removed.

Answer №3

One effective approach involves leveraging the scene's traverse function. This function is present in all objects and allows for a depth-first search through the parent's children.

To see an example directly from Mr. Doob, check out this snippet.

scene.traverse( function ( object ) {
    if ( object instanceof THREE.Mesh ) {
        var geometry = object.geometry;
        var matrixWorld = object.matrixWorld;

        ...

    }
});

Here's another snippet from r82's source code:

traverse: function ( callback ) {
    callback( this );
    var children = this.children;
    for ( var i = 0, l = children.length; i < l; i ++ ) {
        children[ i ].traverse( callback );
    }
}

For specific situations, you can utilize the traverseVisible method like so:

scene.traverseVisible(function(child) {
   if (child.type !== 'Scene') {
      scene.remove(child);
   }
});

Answer №4

The current solution works well, but I aim to offer a more comprehensive explanation for those encountering the same issue with hot module reloading and Three.js. When working with hot module reloading in Three.js, it is often necessary to recreate all objects except for the plane and camera. Here's how you can achieve that:

export const reload = (/* updatedDependencies */) => {
  console.info('Halting the execution loop...')
  cancelAnimationFrame(runLoopIdentifier) // cancelling the previous `requestAnimationFrame` call

  console.info('Clearing all child elements...')
  for (let i = scene.children.length - 1; i >= 0 ; i--) {
    let child = scene.children[ i ];

    if ( child !== plane && child !== camera ) { // excluding the plane and camera objects
      scene.remove(child);
    }
  }

  while (renderer.domElement.lastChild) // clearing the renderer's DOM element
    renderer.domElement.removeChild(renderer.domElement.lastChild)

  document.removeEventListener( 'DOMContentLoaded', onDOMLoad )
  conicalDendriteTreeSegments = require('./plantae/conical-dendrite-trees').default

  initializeScene() // re-initializing all objects in the scene
  runLoopIdentifier = startRenderRunLoop() // starting the rendering loop again

  console.info('Reload process completed.')
}

Answer №5

This approach is proving to be more effective than using traversal (as stated in the Three.js documentation which advises against utilizing the traverse function for making changes to the scene graph). Additionally, it is crucial to remember to properly dispose of geometries to free up memory. By starting with nodes deep within the graph, this method helps prevent memory leaks.

// Clearing all objects
clearObjectsWithChildren(obj){

    if(obj.children.length > 0){
        for (var x = obj.children.length - 1; x>=0; x--){
            clearObjectsWithChildren(obj.children[x]);
        }
    }

    if (obj.geometry) {
        obj.geometry.release();
    }

    if (obj.material) {
        if (obj.material.length) {
            for (let i = 0; i < obj.material.length; ++i) {

                if (obj.material[i].map) obj.material[i].map.release();
                if (obj.material[i].lightMap) obj.material[i].lightMap.release();
                if (obj.material[i].bumpMap) obj.material[i].bumpMap.release();
                if (obj.material[i].normalMap) obj.material[i].normalMap.release();
                if (obj.material[i].specularMap) obj.material[i].specularMap.release();
                if (obj.material[i].envMap) obj.material[i].envMap.release();

                obj.material[i].dispose()
            }
        }
        else {
            if (obj.material.map) obj.material.map.release();
            if (obj.material.lightMap) obj.material.lightMap.release();
            if (obj.material.bumpMap) obj.material.bumpMap.release();
            if (obj.material.normalMap) obj.material.normalMap.release();
            if (obj.material.specularMap) obj.material.specularMap.release();
            if (obj.material.envMap) obj.material.envMap.release();

            obj.material.dispose();
        }
    }

    obj.removeFromHierarchy();

    return true;
}

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

Troubleshooting issue with error handling in graphql mutation hook with react and apollo is not resolving

It seems like I might have overlooked a configuration in my code, but I can't seem to pinpoint where I went wrong. In our application, we have a basic login form. If the correct username and password are entered, everything works smoothly. However, ...

Tips for accessing the 'Show More' feature on a webpage with lazy loading functionality

My aim is to click the 'Show More' button on a website. I have written this code, but an error occurs below it. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait #Launch Chrome driver=webdriver.Chrome(execut ...

Using JavaScript code in ReactJS does not produce the desired results

Just starting out with react and could use a little guidance. I came across this interesting hamburger menu icon on codepen: https://codepen.io/rss/pen/OJxZrR The challenge I'm facing is getting the animation to function properly. import "../.. ...

Using Aurelia to create a schema form

In my project, I am utilizing Aurelia to create a dynamic form based on a JSON data. The form is being generated from a JSON structure similar to the one shown below: Schema = [{ 'key': 'Name', 'display': 'Name&a ...

Can you explain the purpose of `import type {Node} from 'react';` and how it is used in the App component as: () => Node?

Executing the following command: npx react-native init AwesomeProject When reviewing the App.js file, I came across two lines that confuse me: import React from 'react'; import type {Node} from 'react'; // Line 1 import { SafeAreaVi ...

Using JavaScript, what is the best way to retrieve the provided JSON data?

Is there a way to navigate through the JSON structure displayed below? { "question":{ "119380":{ "email":{ "-L8o-zzRRTOJQjI4BQZ0":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="a4c5c6c7e4c3c9c5cd ...

What is the best way to retrieve the status after making an axios call within my express controller?

I'm facing an issue with my express controller setup in returning the correct response. I have an endpoint that should call the address service using axios and return the data, or handle errors by returning a response. However, currently, it defaults ...

Tips for refreshing a list in Angular using a service after form submission

As a beginner with Angular, I am setting up a simple "submit comment" and "display list of comments" page. My goal is to automatically update the list of comments after submitting a new one, without having to manually refresh the page. Here are my control ...

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

The icon is not being displayed when the onHover event on the Material UI component is triggered

I am currently working on adding a delete icon to a Material UI MenuItem component. I've created a state field within the component's state called isHovering, which is initially set to false. The goal is to display the delete icon when hovering o ...

Creating a program to automate block placement

I’m attempting to program my MineFlayer bot to automatically position a sand block on the face of a piston whenever it detects one within a five-block radius. Despite my efforts using bot.placeblock(33, vec(0,0,1), cb), I keep encountering an error mess ...

TypeORM reporting duplication error when bulk saving data instead of detecting and ignoring existing records or updating their values

According to the documentation provided by TypeOrm Framework, the Repository.save function is supposed to save/insert new values and ignore/update existing ones. However, I am currently experiencing an issue where it is throwing a duplication error for an ...

Why isn't the parent view model subscribing to the updating observables in the Knockout component?

I created a component named Upload that enables users to upload files and receive a JSON object containing these files. In this specific case, the Upload component has an input from a parent view model: <upload params="dropzoneId: 'uploadFilesDrop ...

Notifying when a refreshed PHP interactive clock has detected new input

I have created a simple countdown timer in PHP that will continuously update the result to be displayed on the page using JavaScript. I am still deciding whether updating every second could potentially cause any issues. The way the countdown works is by r ...

How can a parameter be added to a query string only when there is a value present in a textbox using JavaScript?

Hello everyone, I am looking to add parameters to a URL only if the search text box value is different from the default. I have three search text boxes and I want to include them in the URL. Below is my code snippet: $("#search-btn").click(function (e) { ...

What is the best way to divide the results of an array into two separate slides

I have a challenge where I need to split an array with over 50 entries into multiple slides, displaying only 14 entries per slide. I've attempted the following code: <div class="mySlides fade"> <div class='content'> ...

Discovering the wonders of Angular's Heroes Tour: What's the magic behind adding the ID in the addHero function

During Angular's official tour of heroes tutorial (https://angular.io/tutorial/toh-pt6), an interesting observation was made. When the addHero method is called, only the hero's name property is passed as an argument. However, it seems that a new ...

How can we integrate fixed-data-table-2 sorting with an existing redux store?

Any help or advice you can offer would be greatly appreciated. I am still fairly new to using react. I recently took on a project for a client that was already in progress, and everything has been going smoothly up until now. I've come across a stumb ...

Naming convention for callback parameters

Exploring a basic node.js code snippet: var fs = require("fs"); fs.readFile('input.txt', function(err, data){ if(err) console.log(err.toString()); console.log(data.toString()); }); console.log('End of the program'); How d ...

Transforming JSON/XML into a hierarchical display

I've come across the following XML file: <Person attribute1="value1" attribute2="value2"> value3 <Address street="value4" city="value5">value6</Address> <Phone number="value7" type="value8">value9</Phone> </Pers ...