This question comes up very frequently so I decided I would create a general explanation of what a Null Reference Exception is. This isn't so much for me as it is for beginners and others new to programming or Unity.
Because the biggest problem appears to be that people new to programming or .Net don't understand what a NullReferenceException means, and it really isn't too hard to fix if you know what your looking for.
So, I'll be posting my explanation. If anyone else has a good explanation, then please post so that there can be one catch-all question for NullReferenceExceptions.
NullReferenceException are thrown when you try to access a reference variable that isnt referencing any object, hence it is null. So the first question, are all variables reference types?
No, in Mono, there are two kinds of variables that are used for most variables: value types and reference types. Value types store a value directly such as an int or a double or any struct such as a Vector3, or an enumeration.
Reference types, on the other hand to not directly store the object data, instead, they store a reference to an object similar to pointers in C/C++. Common reference types are classes, delegates, and strings. Reference types default to null, that is that they are not referencing any object. Hence, if you try and access the object that is being referenced and their isnt one, you will get a NullReferenceException.
Here is another Answer about null references that explains the same thing in slightly different words.
Some common examples:
If you try to get a component that isnt there then try to access it:
Accessing a GameObject that doesnt exist:
Less common, but annoying if you don't know it:
Now to how to fix them: obviously the easiest way to fix them is to not have any NullReferences. But many times thats not possible so you need to have either try-catch blocks or conditionals.
try/catch blocks require that you throw an exception and that does cost resources so more often than not, even though it is sometimes cleaner to read, it isn't as performance efficient.
In simple terms:
A null reference error means something before a dot is null.
(Note: this answer is not technically correct, but it is a pretty good working solution for 99% of beginner null reference exceptions. If you can write a delegate, you can read the documentation and identify your own null references)
answered Jan 04 at 11:27 PM