Looking at other people’s C# code for Unity, I kept seeing this bizarre usage of if:
if (object) { …}
where object was a real object, not a bool instance. This is a JavaScript kind of usage, where there is a big (perceived) mess about object and value types, so I wondered how did C# “automagically” cast to bool? You cannot do that in classical typed OOP languages like Java.
Turns out there is nothing about this in C# itself, its MonoBehaviour that implements implicit boolean casting
public static implicit operator bool($classname$ me){
return me != null;
}
Actually you will have to navigate the hierarchy up to Unity’s Object to find it. See also here.
But if you are learning C# with Unity, be careful as “This can be really confusing because that behavior doesn’t carry over when you start using standard .net libraries and other 3rd party code that is agnostic to Unity.” – here.
And neither it will when writing your classes, when not extending MonoBehaviour, so its not a healthy habit to catch.
Follow me on Twitter where I post about game design, game development, Unity3d 2D, HTML5, serious games.