MonoBehaviour Update called twice, fields being set to null
I was chasing down a null reference exception when I came across something a tad disconcerting.
The (apparently null) field is assigned to in only one placed in my entire code, and before that assignment, I check if the value is null (it never is). And yet, when I try and access it outside of the block in which it gets assigned, I get a null reference exception.
This field is defined in class A, which extends MonoBehaviour.
I have a single instance in my scene of a script B, which extends class A. In an attempt to track down when and how the field is becomes null, I dropped a couple of Debug.Log calls into class B's Update method. Class A does not define an Update method. Using VisualStudio I have double-checked that nowhere else in my code is class B's Update method referenced.
Here is the method...
void Update()
{
if ( target != null )
Debug.Log( "Good reference " + Time.time );
else
Debug.Log( "Bad reference " + Time.time );
}
Somehow, this Update method is being called exactly twice, every frame. Every frame, two lines are output to the console, the first time the method is called, it outputs "Good reference", the second time, "Bad reference."
See the attached imgur link for a sample of my console readout.
http://i.imgur.com/OIBW3n9.png
The stack trace for each Console line looks exactly the same...
Good reference [current time]
UnityEngine.Debug:Log(Object)
MonoToggle:Update() (at Assets/Control/MonoToggle.cs:28)
...for the first line of every frame, followed by...
Bad reference [current time]
UnityEngine.Debug:Log(Object)
MonoToggle:Update() (at Assets/Control/MonoToggle.cs:30)
...for the second line of every frame.
A quick Google search turned up nothing. As far as I can tell no one's ever had this problem.
Did you try logging out the instance id (GetInstanceID) to make sure that you absolutely have just one instance of this script?