if a MonoBehaviour is destoryed, is there a way to find which 'man' destory it?

if a MonoBehaviour is destoryed, is there a way to find which ‘man’ destory it in the onDestroy Method?

No, I don’t think there is, not without pretty ‘ugly’ workarounds anyway.

Why do you need to know? Perhaps there is another way around it.

You can try using the System.Diagnostics.StackTrace class. For example, in C#:

private void OnDestroy()
{
    var st = new System.Diagnostics.StackTrace(true);
    var sfs = st.GetFrames();
    foreach (var sf in sfs)
    {
        Debug.Log(sf.GetFileName() + ", " + sf.GetFileLineNumber());
    }
}

It should work for cases when an object is destroyed explicitly through Destroy or DestroryImmediate. I know that it works for DestroyImmediate, but you’ll have to test it for plain Destory.

HTH

1 Like

wow, thanks, I will test it

I got a question, I have created a lot of rigidbody, and then some of them disappear when their velocity approach to zero, I have no idea, just added a OnDestory to that one of MonoBehaviour belong to that gameObject, I found that OnDestory is called, but I do not know why it happens…

yeah, I failed, the System.Diagnostics.StackTrace get a onDestory at his top, nothing more…