如何在 Update 函数中只设置一次动画命令?

How can i set animation command only once in the Update function?

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

public class Animations : MonoBehaviour
{
    public enum AnimatorStates
    {
        WALK, RUN, IDLE
    }

    private Animator _anim;

    void Awake()
    {
        _anim = GetComponent<Animator>();
    }

    public void PlayState(AnimatorStates state)
    {
        string animName = string.Empty;
        switch (state)
        {
            case AnimatorStates.WALK:
                animName = "Walk";
                break;
            case AnimatorStates.RUN:
                animName = "Run";
                break;
        }
        if (_anim == null)
            _anim = GetComponent<Animator>();

        _anim.Play(animName);
    }

    void Update()
    {
        if (MyCommands.walkbetweenwaypoints == true)
        {
            PlayState(AnimatorStates.RUN);
        }
        else
        {
            PlayState(AnimatorStates.IDLE);
        }
    }
}

代码运行良好,但我认为在更新中多次调用 PlayState 是不对的。如果它是 运行 或 IDLE 状态,我希望在 Update 函数中只调用一次。

一旦 walkbetweenwaypoints 为 true 或 false,它将在 Update 函数中不间断地调用状态。

在 Update 方法中保存最后一个状态,仅当状态实际发生变化时才更新:

AnimatorStates lastState = AnimatorStates.IDLE;
public void PlayState(AnimatorStates state)
{
    if(state != lastState)
    {
        string animName = string.Empty;
        switch (state)
        {
            case AnimatorStates.WALK:
                animName = "Walk";
                break;
            case AnimatorStates.RUN:
                animName = "Run";
                break;
        }
        if (_anim == null)
            _anim = GetComponent<Animator>();

        _anim.Play(animName);

        lastState = state;
    }
}