What is the best way to delete a mesh from an Object3D in a scene?

I have been attempting to delete a specific part/mesh ('olympiaPart2' as an example) from this Object3D:

Object3D {uuid: "78E3A86E-3AF3-4C0F-8805-DE8531F3D512", name: "circle3D", type: "Object3D", parent: Scene, children: Array(1), …}
    castShadow: false
    children: Array(1)
        0: Scene
        autoUpdate: true
        background: null
        castShadow: false
        children: Array(8)
            0: Mesh {uuid: "812FC68F-1421-4C9F-92A9-68D969E955F3", name: "olympiaPart0", type: "Mesh", parent: Scene, children: Array(2), …}
            1: Mesh {uuid: "DF3A40D8-5449-4480-88C3-DDBC2EC5FDAB", name: "olympiaPart1", type: "Mesh", parent: Scene, children: Array(2), …}
-->         2: Mesh {uuid: "80C9467C-95E8-460D-844F-57F37673F745", name: "olympiaPart2", type: "Mesh", parent: Scene, children: Array(2), …}
            3: Mesh {uuid: "12C8660E-80B3-4FBC-BC0B-C72C8AAD8355", name: "olympiaPart3", type: "Mesh", parent: Scene, children: Array(2), …}
            4: Mesh {uuid: "1851A94E-5D8F-4A87-B66C-E1B2C7706B36", name: "olympiaPart4", type: "Mesh", parent: Scene, children: Array(2), …}
            5: Mesh {uuid: "BA629A09-AB2E-499F-AAE0-17A3FB2B18C1", name: "olympiaPart5", type: "Mesh", parent: Scene, children: Array(2), …}
            6: Mesh {uuid: "8D014976-92A5-4290-A876-77F27375EFD8", name: "olympiaPart6", type: "Mesh", parent: Scene, children: Array(2), …}
            7: Mesh {uuid: "3B656568-0C4C-4C69-AE80-7A76E29C496E", name: "olympiaPart7", type: "Mesh", parent: Scene, children: Array(2), …}
            length: 8

I've tried different methods but nothing seems to work so far :

scene.remove( circle3D.children[0].getObjectByName('olympiaPart2') )

and

const removePart = circle3D.getObjectByName('olympiaPart2')
scene.remove(removePart)

Despite no errors being returned and even after checking my scene or object3D with console.log, there is no change in the displayed result.

This is how I created my object3D:

// Circle
const circle3D = new THREE.Object3D
circle3D.name = 'circle3D'
scene.add(circle3D)

const importModel = (_model) => {
    // Using gltf-loader from: www.npmjs.com/package/three-gltf-loader
    let modelLoader = new GLTFLoader()

    modelLoader.load(
        _model,
        ( gltf ) => {
            gltf.scene.rotation.x = 270 * Math.PI / 180

            // Name each mesh for better control
            for(let i=0; i<gltf.scene.children.length; i++) {
                gltf.scene.children[i].name = `olympiaPart${i}`
            }

            // Add to circle3D object
            circle3D.add(gltf.scene)
        }
    )
}

// 'olympia' is the imported gltf model using webpack
importModel(olympia)
//

The desired outcome is to make certain parts/meshes of my object3D disappear after a specific delay/event such as timeout or click. I suspect that my issue might be related to updating either the object or the scene, and despite trying various options, I haven't had any success.

Just in case, here's my loop function:

loop() {
    window.requestAnimationFrame(loop)

    // Renderer & Update
    // Render already manages other animations like rotations & easing for other objects
    update()
    renderer.render(scene, camera)
}

Answer №1

To properly remove the mesh, you should detach it from its parent rather than directly from the scene. Give this approach a try:

const partToRemove = circle3D.getObjectByName('olympiaPart2');
const parentObject = partToRemove.parent;
parentObject.remove(partToRemove);

This solution is tested on three.js R107.

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

Unraveling JSON syntax appears to be an ins

My main challenge is not rotating a DIV, but rather JSON parsing. I need to retrieve the correct attribute value from the variable rotateAttrSet, based on the browser type. I am able to do var rotateAttr = rSET.FF;, however, I am unable to do var rotateAt ...

Jquery encountered a syntax error when a new variable was introduced into the code

I recently implemented a Jquery script to create a drop-down div. $("#top<?php echo $this->$i?>").click(function(){ $("#down<?php echo $this->$i?>").slideToggle("slow","swing",500); }); }); However, this seems to be ca ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

Using a conditional statement in conjunction with the jQuery .animate function

As a complete novice with Javascript and jQuery, I am attempting to animate a div only if a specific variable is true, but unfortunately, it's not functioning as expected. Can someone offer guidance on how to resolve this issue? Below is the code I h ...

You are unable to bind 'ref' while utilizing 'v-for'

Creating polygons inside <svg>...</svg> using v-for: <polygon v-for="id in polygonArr" :key="id" :ref="id" points="15,0 18.541,11.459 30,11.459 20.729,18.541 24.271,30 15,22.918 5.729,30 9.271,18.541 0,11.459 11.459,11.459" /> polygonAr ...

Store the downloaded glTF file in the browser cache to keep it available even after unmounting the component or experiencing a

When a user navigates to the 3D model "scene" on my React website, I load approximately 10MB worth of GLTF models into a three.js scene. After the user finishes interacting with the scene, I perform a cleanup in three.js before unmounting the React compone ...

The ngOnInit function is not triggered upon instantiation of an Injectable class

What could be causing the ngOnInit() method not to be called upon resolution of an Injectable class? Code import {Injectable, OnInit} from 'angular2/core'; import { RestApiService, RestRequest } from './rest-api.service'; @Injectable ...

Using tokens to make consecutive API calls in JavaScript/Node.js

After generating the token, I need to make sequential calls to 5 different APIs. The first API used to generate the token is: POST https://idcs-xxxx.identity.c9dev2.oc9qadev.com/oauth2/v1/token Using the username and password, I will obtain the token from ...

The issue with ngFileUpload causing empty file posts on Safari

Currently, I am utilizing ngFileUpload to transmit images to the Cloudinary service. My application is constructed on Ionic and is meant to be functional on both iOS and Android platforms. The code snippet below showcases my image uploading process: .se ...

Nuxt Vuex global state update does not cause v-for loop components to re-render

I am struggling to effectively use Vuex global state with re-rendering child components in Vue.js. The global state is being mutated, but the data does not update in the v-for loop. Initially, all data is rendered correctly. However, when new data is intr ...

The Yeoman Angular Coffee router is not routing properly and displays an error message "cannot GET"

Struggling with getting the router to load a basic template after setting up a Yeoman angular scaffolder installation. Here's my configuration: // index.html <body ng-app="mvmdApp"> <div class="container" ng-view=""></div>// not ...

Delaying http requests until cache is fully prepared without the need for constant checking

In a unique scenario I am facing, my http requests are caching intermediary results on the server. If the cache is not found, then another server is requested to build it. These requests are sent consecutively (in a loop) using AJAX to a Node Server, with ...

React is struggling to dynamically update text content using button click events

As a beginner in the world of React, Nodejs, and JavaScript, I am exploring onClick events to dynamically change text by clicking buttons. In my practice project, I have an input type="checkbox" that toggles the text between bold and normal style ...

NextJS's Server-Side Rendering makes it incompatible with Reactotron

While setting up the redux store for my NextJS application, I usually rely on the Reactotron library to inspect the store. However, since NextJS involves server-side rendering, importing the configuration in the app file results in an error message saying ...

Why doesn't the 'Range' input type slide on React.js documentation, but it does on CodePen?

Can someone help me figure out why my range slider is not working in my React app? I copied the code from Codepen where it works fine, but in my app, it's not functioning properly. The slider doesn't slide when dragged and clicking on it doesn&a ...

What could be causing my Bootstrap 4 Carousel to not appear on my site?

I followed all the steps to include the Bootstrap 4 carousel code correctly, including adding the necessary libraries and plugins at the end. While the navbar is functioning properly, I am puzzled as to why the carousel is not displaying. Is there somethin ...

Having trouble accessing properties within a JavaScript object array in React.js?

I have a React.js component that fetches its initial state data from an API call in the componentDidMount(). This data comprises an array of objects. While I can see the entire array and individual elements using JSON.stringify (for debugging purposes), a ...

Javascript - Could anyone provide a detailed explanation of the functionality of this code snippet?

Ever since joining a new company 9 months ago, I've been encountering this line of code in JavaScript. It seems to work fine and I've been incorporating it into my coding style to align with the previous developers. However, I'm not entirely ...

Struggling to get moment().utc() to display a two-digit format for the month and year

Currently, I am tackling a bug that has surfaced in a birthday component within my application. This component pulls the date of birth from its props in the format 1997-08-16T00:00:00Z. The challenge I am facing is that when the date of birth is set in the ...

What is the best way to incorporate sorting functionality into my CRUD table?

Below is the backend code snippet: app.get("/sortedcustomers", (req, res) => { db.query("SELECT * FROM customer_info ORDER BY contacted", (err, result) => { if (err) { console.log(err); } else { res.send(result); } }); }); ...