Resetting default animator null reference

When trying to load a save after implementing this code, I get a null reference error.

The error points to these line:

var overrideController = animator.runtimeAnimatorController as AnimatorOverrideController;
if (animatorOverride != null)
{
    animator.runtimeAnimatorController = animatorOverride;
}
else if (overrideController != null)
{
    animator.runtimeAnimatorController = overrideController.runtimeAnimatorController;
}

Error:
RPG.Combat.Weapon.Spawn (UnityEngine.Transform rightHand, UnityEngine.Transform leftHand, UnityEngine.Animator animator) (at Assets/Scripts/Combat/Weapon.cs:34)

So as it is, saving is broken for me, and I haven’t any clue about how to fix it.

Annoyingly too, my scene transition is broken, but that is another issue for later.

Which line in particular is line 34?

Crap, sorry for omitting that.

Line 34 is the first line.

I did some debugging by adding debug lines throughout the code checking for any return, and overrideController always returns null. But it seems to be crapping out in the if/else if block because the debug I put after it never runs, so no output from it.

Yes, the script will stop executing once it hits a Null-reference.
So the most likely reason that this would be null is if animator is null…
You can test this by putting the following before line 34:

if(!animator)
{
     Debug.Log("Animator is null!");
     return;
}

If this is the case, follow the trail back to Fighter. Make sure that you’re passing the animator to the Spawn method.

I seem to have found my issue.

I have done a bit of my own formatting on the scripts to keep things organized for myself, and part of that is caching component references into variables in the start method rather than calling GetComponent every time, and so the animator variable in the fighter script was not set at the time the save was being loaded and calling up EquipWeapon(), and thus was never passed to Spawn(). So my solution is to either call a GetComponent in the EquipWeapon method or to move the caching of the animator to the Awake method.

Thank you for your help. I would have spent ages looking and probably never found it.

As a general rule of thumb, it’s best to cache references to components that are on the same GameObject in Awake() instead of Start(). I’m glad you were able to find the issue.

1 Like

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.