This problem is really eating at my patience, and at this point I’m at a loss.
For some game objects, I put a reference to their script in the controller I’m using to manipulate those instances because it dramatically reduces the amount of code needed to do method calls.
I always do it like this:
private Script reference;
void Start()
{
reference = GameObject.FindGameObjectWithTag ("Object").GetComponent<Script> ();
DoStuff();
}
public void DoStuff()
{
reference.DoALotOfStuffWithOutAllTheAnnoyingExtraCode(foo, bar);
}
And this works, most of the time. But all of a sudden I start getting thrown NullReferenceExceptions in my face from some of these method calls. Sometimes only from certain clones of a prefab! Sometimes, the fix for this is restarting Unity.
Other times, I have to add checks if a reference is null before the method calls, even though I have checked again and again that I have all the syntax correct when I assign the reference in the first place.
An actual example from working code:
I have rooms with four doors leading out from them, each door having three states being open, locked or blocked/hidden.
The door itself has two animations, one for opening and one for closing(when the door is hidden, it’s taken care of by the actual door controller by disabling the renderers of the different parts).
In this case, the animator is the perpetrator:
using UnityEngine;
using System.Collections;
public class DoorAnimation : MonoBehaviour {
private Animator anim;
void Start () {
anim = GetComponent<Animator>();
}
public void CloseDoor() {
if (anim == null) {
anim = GetComponent<Animator>();
}
anim.SetBool ("Open", false);
}
public void OpenDoor() {
renderer.enabled = true;
if (anim == null) {
anim = GetComponent<Animator>();
}
anim.SetBool ("Open", true);
}
}
This is the ONLY way I can make this work.
Has anyone else experienced this?
And by the way, I’m running Unity 4.3.4 on OSX.
Have you tried to run Monodevelop to debug your application and see where and how it obtains the NullException? Have a look at [this][1]. [1]: https://docs.unity3d.com/Documentation/Manual/Debugger.html
– ikelaiahI'll absolutely look into that :) Thanks!
– Discosmurf