Read it all before you conclude it.
I see that there's an accepted answer. But, there is a better answer or suggestion for you for handling
NullReferenceException
. If you can relate programming in Java language like me,
you can prevent from sending a null error by using the try-catch
block. Try it
for yourself! ;-)
If you're using in C#, check if you have using System;
at the top of your script
file. If not, add it. Now, you can use all sorts of Exception
classes while try-
catchingcatching a line of code.
If your're using JavascriptUnityScript, use import System;
Here's an example:
using System; // --> This exact line of code. That's it.
using UnityEngine;
public class Test : MonoBehaviour {
public GameObject player; // --> Example to check if there's a null content;
content;
public void Update() {
// You may now catch null reference here.
try {
player.transform.Translate(0, 0, 2);
} catch(NullReferenceException e) { // --> You may use this type of exception class
}
}
}
Also remember, you can catch also other exceptions such as
MissingReferenceException
, MissingComponentException
,
IndexOutOfRangeException
, or any other exception classes as long as you include
using System
in your script.
That is all.