I'm trying to find out my gameobject is being destroyed by which script in my game.
So far i tried to print stack but details on script which is destroying the gameobject is not mentioned there
code:
Debug.Log(UnityEngine.StackTraceUtility.ExtractStackTrace())

- 61
- 2
-
There may be no way of reporting who called Destroy(obj) not only for GameObject but anything that inherits from UnityEngine.Object in general (components, textures etc). Since Object.Destroy calls internal engine GC system (where this obj is merely an argument) Unity is reluctant to mess with that providing any kind of api. So our only way for that may be just informed guessing and experimental methods. – Andrew Łukasik Dec 29 '19 at 10:27
-
1Suggestion: find **all** instances of `Destroy` calls in you codebase and replace them with `MyTrackedDestroy` which would be your own Object.Destroy-calling method. This will give you the ability to track all/most Destroy calls and log them when needed. – Andrew Łukasik Dec 29 '19 at 10:34
-
if you have a pc goto your scripts folder and do `find "Destroy" *.cs`, on a mac or linux do `grep "Destroy" *.cs` it will show you all scripts with Destroy, or, search for it in visual studio in all files. – BugFinder Dec 29 '19 at 12:39
1 Answers
Destroy
doesn't actually "destroy" the object it's passed right away, it adds the object to a list of objects for Unity to destroy at the end of the frame. This is when when OnDestroy
is called, which is why you won't see the stack for when Destroy
was called (if you'll actually see a stack at all, I'm pretty sure native code will call this).
So that should be the end of it... right?
Well, not exactly. If you check the Order of Execution for Event Functions then there's one event function called before OnDestroy
, OnDisable
.
Lucky for us, not only is this funciton called earlier, but (at least when I last tested this on Unity 2018.4 in play mode in the editor) OnDisable
is actually called by Destroy
, so if you get the stack there, you should, hopefully be able to determine who has been destroying your monobehaviours.

- 155
- 9
-
2
-
1Sadness. In 2020.3, OnDisable is being called stacklessly from the Unity code, like OnDestroy, so this appears not to work anymore? – RealHandy Oct 13 '21 at 01:59
-
1