首页 > 解决方案 > 出于某种原因,当我通过代码要求它时,我的动画没有播放

问题描述

当我使用我的斧头时,我正在尝试播放动画,但是即使我对其进行了编码,它也不会播放。我知道 OnTrggerStay 可以工作,因为在我用来破坏僵尸的另一个脚本中,它被触发了,但它仍然没有动画。这个脚本附在我的斧头上。

(如果代码不好/乱七八糟,我很抱歉)

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

public class Axe_animation : MonoBehaviour
{
    public AnimationClip axeAttack;
    public AnimationClip retractBlade;
    private Animation anim;
    private bool hasAnimPlayed = false;
    private Coroutine animat = null;


    private void OnTriggerStay(Collider coll)
    {
        if (coll.gameObject.tag == "Zombie" && Input.GetMouseButtonDown(0))
        {
            if (animat == null)
            {
                animat = StartCoroutine(Arnim());
            }

        }
    }

    IEnumerator Arnim()
    {
        anim.Play(axeAttack.name);
        hasAnimPlayed = true;

        if (hasAnimPlayed == true)
        {
            anim.Play(retractBlade.name);
            hasAnimPlayed = false;
        }
        yield return new WaitForSeconds(0.5f);
        animat = null;
    }
    

}


标签: c#unity3danimation

解决方案


我相信您的问题是您正在播放 axeAttack 动画,然后立即播放retractBlade 动画。我会研究动画状态。不是从代码中调用动画,而是调用 axeAttack 的第一个状态,然后从状态转换到动画器中的retractBlade,而不是在代码中。另一种选择是这样做:

IEnumerator Arnim()
{
        anim.Play(axeAttack.name);
        hasAnimPlayed = true;

        // need to wait until the next frame for the animator to catch up
        yield return null;

        // wait for the duration of the current animation
        yield return new WaitForSeconds(anim.GetCurrentAnimatorStateInfo(0).length);

        if (hasAnimPlayed == true)
        {
            anim.Play(retractBlade.name);
            hasAnimPlayed = false;
        }
        yield return new WaitForSeconds(0.5f);
        animat = null;
}

在调用另一个动画之前,您需要等待动画完成。


推荐阅读