Unity-仅在动画停止时更改角色

时间:2018-09-17 23:10:37

标签: c# unity3d

我有两个对象(相同的角色,但是功能不同),我想在动画停止和单击触发运行时更改角色。例如,我在Kick_Player处有单击触发的动画,并且当Kick_Player结束动画时,我希望它自动更改为Player_Stopped。姿势互不相同,因为这需要进行这些更改。

我尝试使用this.MyAnimator.GetCurrentAnimatorStateInfo(0).IsName("My_Animation")进行操作,但是尝试失败。有办法吗?

public class TapController : MonoBehaviour {

    Animator Anim;

    public GameObject CharacterToController; //Kick_Player
    public GameObject CharacterToBeStopped; //Player_Stopped

     void Start(){
      Anim = CharacterToController.GetComponent<Animator>();
      CharacterToBeStopped.SetActive(false);
     }

     void Update(){
      if(input.GetMouseButtonDown(0)){
       if(!CharacterToController.activeSelf){
        CharacterToController.SetActive(true);
       }

       Anim.Play("Kick_Ball");


     if(!this.Anim.GetCurrentAnimatorStateInfo(0).IsName("Kick_Ball") {
        CharacterToController.SetActive(false);
        CharacterToBeStopped.SetActive(true);
      }
     }

}

我编写了此代码进行测试,但无法正常工作

1 个答案:

答案 0 :(得分:1)

使用IsName函数要求您在实际动画状态之前为动画状态的基本层名称添加前缀。

默认基本名称通常为“基本层”

enter image description here

if(!this.Anim.GetCurrentAnimatorStateInfo(0).IsName("Base Layer.Kick_Ball") 

请注意,您必须在if(input.GetMouseButtonDown(0)){之外执行此操作,否则将永远没有机会被检查。


我已经看到IsName不适用于某些人的报道,因此,如果您这样做但仍然遇到问题,请考虑采用另一种方式。

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        if (!CharacterToController.activeSelf)
        {
            CharacterToController.SetActive(true);
        }

        Anim.Play("Kick_Ball");

        StartCoroutine(PlayAndWaitForAnim(Anim, "Kick_Ball"));
    }
}


const string animBaseLayer = "Base Layer";
int animHash = Animator.StringToHash(animBaseLayer + ".Kick_Ball");

public IEnumerator PlayAndWaitForAnim(Animator targetAnim, string stateName)
{
    targetAnim.Play(stateName);


    //Wait until we enter the current state
    while (targetAnim.GetCurrentAnimatorStateInfo(0).fullPathHash != animHash)
    {
        yield return null;
    }

    float counter = 0;
    float waitTime = targetAnim.GetCurrentAnimatorStateInfo(0).length;

    //Now, Wait until the current state is done playing
    while (counter < (waitTime))
    {
        counter += Time.deltaTime;
        yield return null;
    }

    //Done playing. Do something below!
    Debug.Log("Done Playing");

    CharacterToController.SetActive(false);
    CharacterToBeStopped.SetActive(true);
}