What could cause a script's reference to an Animator to become null?
I have a prefab that has an Animator and a script controlling the animator. The animator is connected to the script in the editor. The prefab is a character, and I instantiate 2 of them to battle each other. I run through a couple of abilities just fine; their animations are both working. But eventually I get a null reference exception due to animator being null in my script. I don't ever assign the animator variable via script, I link it in via the inspector and then only reference it from there on out. After the null reference occurs I check the instantiated copy of the prefab and sure enough the animator slot on my script is "none". Any ideas?
I added a property that everything now goes through to get the animator.
[SerializeField]
private Animator animator;
private Animator TheAnimator
{
get
{
if(animator == null)
{
Debug.LogError("Animator is null!");
animator = GetComponent<Animator>();
if(animator == null)
{
Debug.LogError("Animator is STILL null after attempting to get the component!");
}
}
return animator;
}
}
While it has never been null after trying to call GetComponent, it frequently loses the reference and has to call GetComponent again. I have no idea why though, there's nothing in my code that touches the animator besides getting and setting its parameters
Answer by Grateyfratez · Sep 06, 2015 at 04:45 PM
Turns out I was editing an animation when I linked the animator to the script. Apparently linking references is something the animation can automate.
Answer by getyour411 · Sep 05, 2015 at 05:57 AM
That's how prefabs are. You have to set the external references/Getcomponent calls via it's Awake/OnEnable/Start.
The animator and the script are on the same gameobject, so I link them in the editor via drag and drop and apply it to the prefab. The reference remains intact for a while during gameplay and then eventually it just disappears.
Your answer
Follow this Question
Related Questions
Unity animation doesn't work after time delay or when accessed from another script? 0 Answers
MobController 1 Answer
FPS Controller bug? 0 Answers
NullRefrenceException - Cant find the cost 1 Answer
Animation State not working 1 Answer