- Home /
Null component is not null?
After getting component its reference is not null if component not exists, https://pastebin.com/wAvRLTkP problem at line 34:
if (RootRigidbody == null)
If RigitBody2D not exists it returns object with null reference but not null, if replace it with
if (RootRigidbody.Equals(null))
It will work fine, but I don't understand this behavior, can you say what I'm doing wrong? Reference is not null: But component is missing:
Answer by _dns_ · Apr 26, 2017 at 04:11 PM
Hi, it must be because Unity redefines "==" operator on Monobehaviors. You can get more info in Unity's blog post here: https://blogs.unity3d.com/2014/05/16/custom-operator-should-we-keep-it/
Note that this is actually a mis-interpretation of the debugger. It displays the result of System.Object.operator ==
while the actual code uses the UnityEngine.Object.operator ==
.
If you actually step through you will notice that the code does enter the if body and does Add the Rigidbody2D component.
Also, as you can read in the blog post, the fake null object is only returned by GetComponent when you test inside the editor. At runtime in a built game it will actually return null. In most cases it doesn't make any difference due to the overloaded == operator. However you may get in trouble when you cast a UnityEngine.Object derived reference type into System.Object. operators are not virtual methods. So when using the == operator on a System.Object reference it won't use Unity's and actually "see" the fake null object.
Even though GetComponent won't return fake null object in a build, you can still have fake null objects. Whenever you destroy an object it becomes "fake null" as well.
Your answer
