Null values in Unity

Just wondering what is the right way to represent null values in Unity/JavaScript in Unity? I’ve seen lots of different ones used:

  • null
  • nil
  • undefined
  • NaN

I’m using null at the moment but It’d be nice to have an explanation of what’s right for each language? Just in case :slight_smile:

Cheers,

  • James

You should almost always want to use null.

  • nil is used in some languages including Objective-C, but isn’t used in js or C#.

  • I’ve never seen anyone set a variable to undefined. I’ve gotten error messages saying I’ve used an undefined type, but I’ve never intentionally set it to undefined. (Uninitialized is different)

  • NaN is for Not a Number. You get this when you divide by 0. Its a specially defined constant just like infinity that doesn’t behave like normal floats. This comes up when you are making sure that you don’t accidentally assign a NaN to a Unity property. Example:

      if(!System.Single.IsNaN(someValue))
            transform.position.x = someValue;
    
  • Null is for reference types that aren’t referencing any objects at the moment. This is the default initialized state of reference types. You usually want to do this. It has equivalent meaning to nil. Its just the right keyword for the language.