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:
- We can clearly see that the reference has been assigned via the Inspector
- 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
if(headingaccuracy != null)
{
headingaccuracy.text = "Heading Accuracy ";
}
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
{
headingaccuracy.text = "Heading Accuracy ";
}
catch(NullReferenceException exception) // using an error type, like this, requires System.
{
// we have hit a NullReferenceException, so apply this logic, instead.
Debug.Log("WARNING: headingaccuracy not set up on " + gameObject.name);
}