Checking for null reference

Until about 10 minutes ago, I used to always check for null reference like so:

if (someVariable)
{

//do stuff

}

This has worked for me on every script I have ever wrote until now. The only thing I’m doing differently is checking if a variable of my own custom type is null whereas before I would always be checking if a unity type (collider, animator, rigidbody etc). I’ve done some googling but cannot even find examples where people check for null referencing the way I do so now I’m thinking how have I been able to do it so far. Any help?

Try adding the following to your custom type. There may be a nicer way to code this. Untested, so no guarantee it will work.

public static implicit operator bool(SomeVariable someVariable)
{
    if (someVariable == null) {
        return false;
    } else {
        return true;
    }
}

Edit:

This has been bouncing around in my head and I have two other solutions to propose.

  1. Inherit from ScriptableObject

  2. Change your checking logic to:

    if(someVariable != null)