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是正确的。我希望如果它的RUN或IDLE状态在Update函数中只调用一次。
一旦walkbetweenwaypoints为true或false,它将在Update函数中调用状态不间断。
答案 0 :(得分:1)
在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;
}
}