- Home /
UnityEngine.Object is null but System.Object is NOT null!
public class JJJ : MonoBehaviour
{
void Start ()
{
Component com = gameObject.GetComponent(typeof(UnityEngine.SkinnedMeshRenderer));
if (com == null)
print("com == null");
else
print("com != null");
Print (com);
}
void Print(object obj)
{
if (obj == null)
print("obj == null");
else
print("obj != null");
}
}
Output:
com == null
obj != null.
Why is com null but obj is not null?
This gameObject does not have SKinnedMeshRenderer attached.
Thank you
Answer by Bunny83 · Oct 24, 2015 at 07:32 AM
There are already tons of threads and questions on that topic:
http://answers.unity3d.com/questions/524998/testing-for-null-bug-or-feature.html
http://forum.unity3d.com/threads/null-check-inconsistency-c.220649/
http://answers.unity3d.com/questions/731469/non-null-object-with-working-properties-evaluates.html
http://answers.unity3d.com/questions/1040391/what-so-many-bizarre-designs.html
Answer by SniperEvan · Oct 24, 2015 at 05:47 AM
Could be because UnityEngine.Object overrides the equals function. I know when you call Destroy (object) and then check for null Unity returns null even when the object hasn't been cleared from memory yet. My point is that unity is doing some extra management and I think if the object exists it doesn't return null.
I'm not sure if that helps.
Answer by Matheuz · Apr 07, 2020 at 07:50 PM
In a summary: there are 2 objects that live in different worlds: a C# script (your code) and its engine (native) components, like transform and gameObject. The lifetime of the C# objects is determined by the garbage collector and it won't point to null unless you explicitly do it. The lifetime of the engine components is determined by calls to Destroy. Thus, a MonoBehaviour's engine components are destroyed when you call OnDestroy, but its C# object will live as long as you keep a reference to it. This article explains it better.
Your answer
![](https://koobas.hobune.stream/wayback/20220612042513im_/https://answers.unity.com/themes/thub/images/avi.jpg)