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?

1 Answer

1

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…

–