Why do if statements in Unity3d C# allow objects that are not bools?

后端 未结 1 973
无人共我
无人共我 2020-12-10 18:14

In the standard .NET 4.6 compiler, the following if statement is not legal, you will get the compiler error: CS0029 Cannot implicitly convert type \'UserQuery.TestClass\' to

相关标签:
1条回答
  • 2020-12-10 18:42

    Don't worry too much about this. The if (obj) is only legal in Unity because there is implicit operator overload in Unity. I believe that was done in the MonoBehaviour or UnityEngine.Object class.

    It looks something like this:

    public static implicit operator bool($classname$ other){
        return other != null;
    }
    

    Unity planed to remove this feature but decided to go against it because it would break every Unity code out there. You can read more about this here.

    The very bad side of this feature is that it made it impossible to use the Null-Coalescing operator feature in the Editor. The good side is that it s simplifies checking for null.

    0 讨论(0)
提交回复
热议问题