- Home /
Destroy object before end of Awake function
I'm trying to destroy an object in Awake but if I use the Destroy(gameObject) call, it will continue running the code in the Awake function until the end. How can I destroy it immediately and not run anymore code from that point?
Answer by whydoidoit · Apr 04, 2013 at 04:17 AM
You just need to "return" after you've destroyed it. It will also continue to exist for that frame unless you use DestroyImmediate.
Hmm… I saw DestroyImmediate but the documentation is very specific of warning people away from using that in game code.
Is it safe?
Just saw this comment from Eric on this question, kinda gives me the info I was looking for: http://answers.unity3d.com/questions/18651/Difference-between-Destroy-and-DestroyImmediate-.html
I wish there was a little more info in the documentation of WHY they warn against it though, just so I can be careful of its use.
It's reasonably safe so long as you know what you are doing. The idea is that in a frame all of the objects should exist because perhaps there's some interaction going on between scripts, it might screw up physics if you did it in there for instance, not sure. I use it without a problem when necessary, but only do it when I must.
I just tested this and DestroyImmediate isn't as immediate as I need it to be. It's still continuing to stay alive so that other objects can Find it. :(
I guess I'll have to re-work my code to figure out another way to make this work…
Your answer
![](https://koobas.hobune.stream/wayback/20220613095645im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
using Contains(gameObject) to find and destroy a gameObject from a list 2 Answers
Destroy an enemy when it touches an object 2 Answers
Destroying an object when it collides with another 1 Answer
Instantiate JS error that i can't figure out 1 Answer
destroy a non-trigger object hitting a trigger object? 1 Answer