NPC Animation

Animator

The easiest way to create animation for an NPC is to have the character execute a single animation state like idle, created by dragging a set of sprites into the scene view. In order to create more interesting animation, a custom script needs to be added to the NPC as shown below.

NPC Animation: Animator, Coroutine, Button

The following is a simple script that use a co-routine to have the NPC have a delayed switch between 2 animator states. Configure the Animator states as you did with the Player, however in this case, use "NPCState" as the name of the animator integer parameter that controls the transitions between animation states. The public methods allow for changing the state of the NPC from some other object such as a UI-Button as shown in the image below.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

//attach to an NPC that has animator controller
//adjust as necessary for 
public class NPCAnimation : MonoBehaviour
{
    // Start is called before the first frame update
    enum NPCState {  idle, attack}

    Animator animator;

    void Start()
    {
        animator = GetComponent<Animator>();
        animator.SetInteger("NPCState", (int)NPCState.idle);
        StartCoroutine(NPC_Animation());
    }

    //looping transistions between states: idle, attack

    IEnumerator NPC_Animation()
    {
        while (true) // you can put there some other condition
        {
            animator.SetInteger("NPCState", (int)NPCState.idle);
            yield return new WaitForSeconds(5.0f);
            animator.SetInteger("NPCState", (int)NPCState.attack);
            yield return new WaitForSeconds(5.0f);
        }
    }

    public void SetIdle()
    {
        StopCoroutine(NPC_Animation());
        Debug.Log("StopNPC_CoroutineAnimation");
        animator.SetInteger("NPCState", (int)NPCState.idle);
    }

    public void SetAttack()
    {
        StopCoroutine(NPC_Animation());
        animator.SetInteger("NPCState", (int)NPCState.attack);
    }


}

Last updated