- Home /
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?
I'm guessing your custom type does not have a definition for the bool operator. Will get back to you on how to define one.
Ahhh I see. I always thought that it was built into c#. Previous languages I've used have allowed if (variable) to check if an int is 1 or 0, a reference as null and a bool as true/false so I presumed c# would check for null and bool. Thanks for your help aswel, I appreciate it!
Answer by Kiwasi · Jun 19, 2014 at 03:40 AM
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.
Inherit from ScriptableObject
Change your checking logic to:
if(someVariable != null)
use double equal sign ins$$anonymous$$d of a single equal sign if (someVariable == null)
and you can archive the same goal with a single line like this:
return someVariable == null ? true : false;
I vote that the next update to UA includes a check for compile time errors when you hit the code button.
Failing that I will edit in the second equals sign.
I knew there was a single line implementation, just not a syntax I commonly use. Thanks for adding it.
Just
return someVariable == null;
is fine, no need for ternary operators.
I told you there may have been a nicer way to code it. Thanks!