Handling Errors
So you want unity to ignore the Null-Reference error? well all you do is check if its null and return if its null. To do this we need to Catch the Error when it happens withing that level of code. this will bypass the halting effect that errors usually have(catching will not work with compiler errors!)
The Try and Catch Keyword
The try keyword is used to run code that may or may not work correctly, the code inside is refereed to as “guarded code”. code inside try will run like normal until an exception is found this is where out catch comes in. Every time you get a run time error, your computer will look for the catch statement that handles that specific error.
if no catch statement is found then the program is halted until the error is fixed or the programmers adds the handling.when there is a catch statement, the compiler will run the code withing the catch statement without halting the program. Unity handles exception in a way so that when you get an exception, An error message appears in the Unity console and halts that code, not all of unity itself.
there is also a finally keyword along with catch and try but its not needed here.
Usage
we put the code we want into the try statement. then below it we pass an error type to the catch statement. in this case its is the dreaded NullReferenceException. Now when anything in that code gets a Null referencing Exception, instead of halting execution the catch statement will run, from here I like to add a debug statement so I know that the error is there and is being caught. then we can just call a “return” statment.
something like this
try{
if( blast.GetComponent<InstantiateBlast> ().blasting) {
anim.SetBool("Jumped",true);
}
}
catch(System.NullReferenceException ne) {
Debug.Log("Null reference Exception: Your Arguement is Invalid "); //tells you the error, but does not hinder the code from running
return;
}
Yes there are called try and catch statments see here:
Give it a read, try-catch and finally statements fit this purpose as you don’t always know if something will be there.
Edit: Yes, most scripts i post are usually a guide not a paste off solution.
also note don’t just whack a catch statement every time you get an error, this will cause more bad than good