Can't get animator.Play() to work in other script

My orc gameobject has a script called MinionAttack.cs with this code:

public Animator animator;
void Awake ()
{
    animator = GetComponent<Animator>();
}
public void TookAHit(int numDamage = 5)
{
    animator.Play(enemyType + "_Hurt");
}

In my Hero gameobject I have a script that does this:

// at the top
public GameObject minion;

// down in a function
minion.GetComponent<MinionAttack>().TookAHit(10);

I have dragged an Orc prefab into the correct spot in the IDE to fill in that minion variable.

What happens when I try to call TookAHit() is that I get this error message:

UnassignedReferenceException: The variable animator of MinionAttack has not been assigned.
You probably need to assign the animator variable of the MinionAttack script in the inspector.

Other animation inside the MinionAttack script work fine, but they’re being called from inside that same script (Trigger stuff). When I look at the animator variable in the IDE I can see that the code inside Awake did the job and it’s not null, so I’m not sure what that error message means.

Is this enough info for someone to let me know what boneheaded move I’m pulling?

Thanks.

Jay

Is that code inside some sort of collision detection?

It’s inside a function where my hero swings his sword. The TookAHit() function makes the Orc react with a “hurt” animation. So no, it’s not in a collision detection function, but it’s inside a function, not just hanging out in the middle of nowhere.

Jay

My guess is that your Hero is trying to access the prefab you assigned in the inspector but as it’s not instantiated in the scene Awake is never called. If that’s the case you have to get the instance of your Orc that’s alive in the scene. That’s usually done with colliders but might not be the case.

Thanks for the guess – I’m pretty sure that’s not the problem because when the scene loads the Orcs are all instantiated and I can click through them and see that everything appears to be ready to go.

In addition, some of the other animation.Play() things inside MinionAttack fire off as the game goes along – it’s just trying to call one from another script that’s causing a problem.

Thanks for taking a look at it.

Anyone else have any ideas?

Jay

I figured it out – and technically, solkar was correct in what was happening.

While I had everything in the right spot, when my Hero would attack the NPC, it was referencing a “generic” Orc and not the Orc that was in front of him. So the Orc prefab – and in that one, Awake was never being called.

I was attempting to manipulate the prefab, not the instantiated version.

Jay

1 Like