By destroying an object, I also remove the material from other objects with the same material

Hi, I run into a situation, where I need to destroy an object, but by doing so, it also removes the texture/material from other (not destroyed objects). I use the same Matierial for a couple of objects.
I suppose my

for (let i = 0; i < this.additionalDecorationSnowman.children.length; i++){
                                               GameObject.destroy(this.additionalDecorationSnowman.children[i],true);
                                            }

also deletes the used material, even if other objects using this material are still in this scene.

Is there an elegant way to keep the material?

Original Post on Discord

by user 743203108271816774

Hello there – we have an experimental AI bot :robot: that might be able to help you with your question. Would you like to try this out?

How it works:
Reply to the messages of the bot that end with a thread_id to interact with it and ask follow-up questions. You can also mention the bot directly in this channel to get help.

Help requested: please wait a moment…

Hello Krempel,

When you destroy a GameObject with the true argument, it will dispose of all associated materials and geometries, which can accidentally affect other objects sharing the same material. To avoid this, you can set the argument to false to leave materials and geometries intact. Here’s a revised version of your code:

for (let i = 0; i < this.additionalDecorationSnowman.children.length; i++){
    GameObject.destroy(this.additionalDecorationSnowman.children[i], false);
}

By setting the second argument to false, the GameObject.destroy method should not dispose of the material, allowing other objects using the same material to remain unaffected.

1 messages left GPT 4
thread_kAEOOXA9fv2z13ibJo1NFQki

Hi, dont fully believe the bot here. The problem is that the third argument is also disposing the resources and it seems its not detecting that your material is still being used.
Can you try calling GameObject.destroy(this.additional...., true, false) (setting the third arg to false) ?

Is the material by any chance using instancing?

Btw out of curiousity: why do you loop the children anyways?

You can just call GameObject.destroy(this.additionalDecrorationSnowman, true, false) without the forloop

@marcel :cactus: thanks, it worked! No, no GPU instancing is used

by user 743203108271816774

@marcel :cactus: I reference this parent object from other scripts and and thought it is more save to just delete the children , to prevent missing references

by user 743203108271816774