When attempting to remove an object from the scene, an error occurs stating that children[i]

Is there a way to remove an object from the scene?

removeObjectFromScene = (position) => {
    this.scene.traverse((child) => {
        if (child.isGroup && child.userData.position) {
            if (child.userData.position.equals(position)) {
                console.log(child.name);
                this.scene.remove(child);
            }
        }
    });
}

Encountering an issue:

object_113

Uncaught TypeError: children[i] is undefined
    traverse three.module.js:7944

I would appreciate any suggestions on how to resolve this problem. Thank you.

Answer №1

Possible Issue
In a THREE.Group, it is possible to have THREE.Mesh/Three.Object3D as its children. Therefore, when you traverse and eventually remove this group, you are also inadvertently removing its children. As a result, the traversal may encounter an index that references a child that has already been removed.
https://i.sstatic.net/t4CiQ.jpg The following solution could potentially resolve this problem:

const removeLegoByPos = (pos) => {
    let LegoToBeRemoved = undefined

    this.scene.traverse((child) => {
        if (child.isGroup && child.userData.position) {
            if (child.userData.position.equals(pos)) {
                LegoToBeRemoved = child
                // If you find the group, consider researching if traverse can be stopped mid-process, as I am uncertain
            }
        }
    })

    if (legoToBeRemoved) {
        legoToBeRemoved.removeFromParent()
        return true
    }

    return false
}

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

Is your Z-Index failing to make an impact?

Currently, I am attempting to layer divs on top of a background image. All the elements have designated position attributes, and I have applied a 50% opacity to the background image so that what's behind it is partially visible. Despite setting the z- ...

Is there a way to avoid getting a 404 error in Express when using multiple static directories?

I am working on serving files from two different folders to keep my admin and client content separate. The code I have set up initiates the two folders, but when Express looks for a file like example.css, it first checks the /static directory. If it doesn ...

Enter information into the designated text field once you have selected the button

In my PHP/HTML form for user login, I have a password field where users can enter their password or click a button to generate a random one. Although I found some JavaScript code online for this feature, I'm having trouble getting it to work with my ...

A user-friendly JavaScript framework focused on manipulating the DOM using a module approach and aiming to mirror the ease of use found in jQuery

This is simply a training exercise. I have created a script for solving this using the resource (function(window) { function smp(selector) { return new smpObj(selector); } function smpObj(selector) { this.length = 0; i ...

Verify the presence of blank space with javaScript

I currently have a text box on my website. <input type="text" name="FirstName" value="Mickey"> My goal is to prevent the user from entering empty spaces, tabs, or new lines in the text box. However, I want to allow spaces between characters. Does a ...

Unable to get Discord.js sample code functioning correctly

Despite my best efforts, I can't seem to figure out why this simple example code is not working. As a newcomer to Java Script, I am struggling with understanding why the line GatewayIntentBits.Guilds is causing an error. Surprisingly, when I comment o ...

How can I choose which button to click in selenium if there are multiple buttons on the page with the same name, value, and id?

This particular button actually opens a popup, even though it is located on the same page. ![click here for image description][1] I attempted to interact with the element using the following code: driver.findElement(By.tagName("td")).findElement(By.id( ...

Which is the more precise approach: res.render('test') or res.render('test.ejs')?

When it comes to coding, I have my own unique style app.set('view engine', 'ejs'); app.get('/test', (req, res) => { res.render('show.ejs'); }) However, it seems that most developers and documentation don&ap ...

Disregard the sorting of rows in the MUI Datagrid

Any advice on excluding the "TOTAL" row from sorting in MUI library? onSortModelChange={(test, neww) => { neww.api.state.sorting.sortedRows = [14881337, 2, 3] neww.api.setState({...neww.api.state}) } } Review ...

Enabling the use of jQuery with Angular instead of JQLite

According to the angular DOCS, if jQuery is available, angular.element is an alias for the jQuery function. If jQuery is not available, angular.element delegates to AngularJS's built-in subset of jQuery, known as "jQuery lite" or jqLite. In an attemp ...

As the background image shifts, it gradually grows in size

I'm attempting to create an interesting visual effect where a background image moves horizontally and loops seamlessly, creating the illusion of an infinite loop of images. Using only HTML and CSS, I've run into an issue where the background ima ...

"Unveiling the power of canvas layers in creating dynamic

Curious about the process of achieving this task. Draw, pause for 1 second. Draw frame 2, pause for 1 second. Draw frame 3, pause for 1 second. Clear animation canvas. I believe the solution involves working on an overlapping canvas to avoid being erased ...

Looping through an array

I have created an array as shown below: iArray = [true, true, false, false, false, false, false, false, true, true, true, false, true, false, false, false, false, true] Condition check: If any value in this array is false, I will display an error messag ...

Can the renderWith function of a column in angular-datatables retrieve a value from a promise?

Can I trigger a call to a service or filter that retrieves a promise from the renderWith() function of a column? When I attempt this, the result always appears as "[object Object]". vm.dtInstance = {}; vm.dtOptions = DTOptionsBuilder.fromFnPromise(MySe ...

Using ajax.actionlink to display the desired text

When using an ajax.actionlink @Ajax.ActionLink("Add Last Name", // <-- Text to display "AddTimeSeriesData", // <-- Action Method Name etc.... @id = "link") How can I extract the link text in JavaScript? I attempted to use $(&apo ...

Having trouble loading the DOM element within the child component

An issue has arisen with Angular 4.4.6 regarding the access of a DOM element by ID from a different component. Within my component, I aim to display a Google Maps for specific purposes. Following the examples given in the API, I include the following code ...

Searching for data in Express JS with MongoDB using the $or operator is not possible

I am currently developing an API for managing my invoice data. Within this data, there are boolean values that determine the status of the invoices. For example, some invoices are marked as 'payment received', and I need to search for those speci ...

What is the best way to customize the appearance of an Angular tree component?

I'm attempting to incorporate the style of the ACE Admin theme into the angular-tree-component. Currently, my tree looks like this: https://i.sstatic.net/ktiEf.png However, I desire to apply styles from the Angular tree guide in order to achieve a ...

The first-person control feature in three.js has a glitch that causes objects to vanish from the

Can you please take a look at this Three.js snippet I found here: http://jsfiddle.net/ahmedadel/GUr6y/3/. The issue I'm facing is that the objects disappear from the scene after any navigation event (e.g. pressing w, a, s, d) or clicking when the came ...

What is the correct way to encode this URL using JavaScript or jQuery?

My goal is to properly encode the link below, but I seem to be encountering an issue with the "#" symbol: var text = "hello, how are you? &am fine"; var link = "http://example.com/test#zzzzzzzzz"; url = "http://twitter.com/share?url=" + link + "& ...