# Why would I receive a NullReferenceException when the object is clearly set, and still works?

I am getting the exception "NullReferenceException: Object reference not set to an instance of an object" while changing text of a user interface text field, even though the text changes successfully, as you can see in the image. It still gives me a null reference exception; if it was not set, then how can it change the text?

I don't know what is happening, here. I have re-imported the project, but the problem stays.

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

{

public Text rawvector;

private void Start()
{
}
}

• Is the error popping up every time you run it? – Aditya Yadav Apr 28 '17 at 6:42

I have ran into this problem more often than I care to remember. First and foremost, there is no NullReferenceException in the script associated with "emptyTest". We know that for two reasons:

1. We can clearly see that the reference has been assigned via the Inspector
2. We only have one line of code, and as you confirm, it is successfully running. A NullReferenceException infers that the line did not successfully run, and if there was a null reference, we certainly would not be able to edit a value with in that referenced class.

The solution is simple. You have another instance of Menu running, somewhere. I would speculate that it is attached to an object in your canvas, as the working model you show us appears to be a test game object. This happens to me all the time.

The easiest solution is to try Debug.Log(gameObject.name); before the first line of your Start() method. Before the instance hits a NullReferenceException, it will output the name of the game object. This will tell you exactly what game object has the non-setup version of Menu, instead of having to procedurally check each one.

You could also change your logic to anticipate such problems, in the future. The common approach is to simply check if a reference is valid, before using it. An alternate is to simply use a try..catch statement in anticipation of the specific error.

// The simple "check if null, first" approach
{
}
else
{
Debug.Log("WARNING: headingaccuracy not set up on " + gameObject.name);
}

/* -------------------------------------------------------------------- */

// The more complicated "try/catch" approach (make sure your using the System namespace)
try
{