How do I make my enemies animate independently from one another?

I’m trying to do a simple animation for my prefab of enemies where if they are in attack and sight range (i.e. close enough to the player to attack them) they will stop and do an attack animation. And if they aren’t in attack range, but in sight range, they will instead do a running animation towards the player. They will then stop and switch to doing the attack animation when they are now in attack range as well as sight range.

However, I’m clearly not doing something right because what’s happening is the enemies are always doing the animation for running towards the player and only do the attack animation after they have all reached the attack range.

Here’s my code:

public class AnimationStateController : MonoBehaviour
{
    Animator animator;
    private GameObject enemy;
    // Start is called before the first frame update
    void Start()
    {
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        Enemy enemy = FindObjectOfType<Enemy>().GetComponent<Enemy>();
        if (enemy.playerInSightRange && !enemy.playerInAttackRange)
        {
            animator.Play("RunForward");
        }
        else
        {
            animator.Play("Idle");
        }
    }
}

“enemy.” is used to get the Enemy script’s “playerInSightRange” and “playerInAttackRange” variables.

Thanks for the help.

If your component here is on the same enemy game object or prefab, don’t use FindObjectOfType. Either use GetComponent like you are with the Animator, or expose and assign it via the inspector.

Currently each component will probably be finding the same instance (first in the hierarchy), rather than their own instance.

2 Likes

Thank you so much!

I got the result that I wanted by using “GetCompenentInParent();”.

I appreciate your help a ton!

1 Like