Hello guys. I am working on a project and I have several functions capable of destroying an object.
I would like to know if there is a way to print the name of the function which destroyed triggered the OnDestroy() function of my destroyed object.
Thanks a lot in advance.
Edit: Right now I am printing the name of the function on each function before I call GameObject.Destroy(obj)… However, I think there should be another method(?)
I don’t think Unity provides a way to detect who destroyed your object using only the OnDestroy message.
However, you can define a custom class which inherits from MonoBehaviour to have the possibility to track it :
public class MyMonoBehaviour : MonoBehaviour
public void DestroyGameObject( MonoBehaviour caller = null )
if( caller != null )
Debug.Log( gameObject.name + " has been destroyed by " + caller.gameObject.name ) ;
GameObject.Destroy( gameObject ) ;
To destroy the gameobject, use :
MyMonoBehaviour myMonoBehaviour = otherObject.GetComponent<MyMonoBehaviour>() ?? otherObject.gameObject.AddComponent<MyMonoBehaviour>() ;
myMonoBehaviour.DestroyGameObject( this ) ;
It may not be the simpler way, but I think, it works !