- Home /
How to catch NullReferrenceExceptions in void Update
I am currently working on a camera to follow a Game Object with a tag "Player". I was trying to make the camera auto-track the player once they're destroyed/gone on the scene however I am getting a NullReferrenceException error and it's kinda annoying showing on my console and I believe it would cause problems on the game I've been working on.
Here's how I tried to approach the problem:
void Update()
{
if (playerObject == null) //if no object that has "Player" tag found
{
Debug.Log("Camera Status: Finding player");
try
{
tracker(); //a function that contains the line where it finds the "Player" tag.
}
catch (NullReferenceException ex)
{
Debug.Log(ex); // Just a code trying if it works
}
}
}
I also recently tried to transfer that on the LateUpdate but still remains the same. How do I handle this error in Unity?
if playerObject is used inside of the tracker() method then it trow the null exception because playerObject is null always for this method.
It would be helpful to know what code (in tracker()) is triggering the null reference, and possibly why. I would hope it would be possible to fix that code so it never throws an exception.
Answer by Bunny83 · Aug 23, 2017 at 04:44 PM
Catching a null reference exception is never a solution. A NullReferenceExceptions is a breaking condition from which the current method can't continue. You should find the cause and remove it. Some platforms don't even support catching exceptions.
Like the others have mentioned the code you posted does not show the problematic part, so it's doesn't belong into the question. Your question should focus on the problem and not on a possible solution.
Your answer
Follow this Question
Related Questions
3d platforming Camera 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
"Follow Target" script with a prefab (C#) Help me please! 1 Answer