- Home /
How do I properly destroy an instance of a prefab from within its own script?
Here's the setup: I have a platform, this platform is attached to a blank GameObject called Pusher with an animation and script component. That is to say the empty 'container' object has the animation and script components as well as the child 'platform'.
Pusher is designed to push a few blocks sitting on it up, then create a new instance of itself (along with a few more blocks right under the previous blocks), then delete itself. The new instance does the same thing until I tell this whole process to stop.
The whole thing works great. The only problem is in my editor, in the Heirarchy View, next to the 'Pusher' prefab I see (clone)(clone)(clone)... for as many times as this process has repeated itself. I imagine it has something to do with not completely deleting itself. Again, it works aside from that being, what I can only imagine, a massive memory issue. I've listed the code below; any help would be fantastic.
void CreateNewPusher() {
this.isAtTop = false;
Instantiate(this.pusherPrefab, this.originPoint, this.transform.rotation);
GameObject.Find("Block Factory").GetComponent<BlockFactory>().CreateNewLine();
Destroy(this.gameObject);
}
Answer by Adam Rademacher · Oct 04, 2010 at 05:35 AM
You can get around this by reassigning the name on instantiation...It's nothing to do with the objects not deleting themselves, they're just cloning themselves before they get destroyed again, adding an additional (clone) to the end each time.
void CreateNewPusher() {
this.isAtTop = false;
GameObject newPusher = (GameObject)Instantiate(this.pusherPrefab, this.originPoint, this.transform.rotation);
newPusher.name = "Pusher";
GameObject.Find("Block Factory").GetComponent<BlockFactory>().CreateNewLine();
Destroy(this.gameObject);
}
That worked great! So it's not that there were ever multiple instances, just that the name kept getting the (clone) appended to the end; that does answer why the (clone)s were all on the same 'object' rather than making the list longer. Thank you!!
Comments are not supposed to go in the answer section.
Your answer
![](https://koobas.hobune.stream/wayback/20220613074649im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Destroy instance clone of gameobject 2 Answers
Duplicate Object, by dragging? (SporeCreatureCreator Like) 0 Answers
How to destroy gun bullet clone? 1 Answer
How do I assign a script to a clone through another script? 1 Answer
destroy child object 2 Answers