我在Unity上工作,我想做的是:在10秒内播放AnimationType。我希望代码循环播放动画,每个动画播放10秒。代码运行时没有错误,只是结果不是我期望的那样。它播放第一个动画,拳击,持续10秒,就在它即将播放背面动画时,它开始对角色做一些奇怪的事情。这就是问题所在。
这是我的代码:

public class BeBot_Controller : MonoBehaviour
{

    Animator anim;
    string animationType;
    string[] split;
    int arrayLength;

    void Start()
    {
        //AndroidJavaClass pluginClass = new AndroidJavaClass("yenettaapp.my_bebot_plugin.My_BeBot_Plugin");
        //animationType = pluginClass.CallStatic<string>("getMessage");
        animationType="Null,Boxing,Backflip";
        split = animationType.Split(',');
        anim = gameObject.GetComponentInChildren<Animator> ();
        arrayLength = split.Length;

    }

    // Update is called once per frame
    void Update () {
        if (arrayLength > 1){
            StartCoroutine ("LoopThroughAnimation");
        }
    }

    IEnumerator LoopThroughAnimation()
    {
        for (int i = 1 ; i < arrayLength; i++) {
            animationType = split [i];
            //anim.SetInteger ("AnimPar", 0);
            anim.Play (animationType);
            yield return new WaitForSeconds (10);
        }
    }
}

我在这里做错了什么?我还有别的办法可以解决这个问题吗?

最佳答案

由于只需要调用一次动画循环,只需将StartCoroutine()移动到Start()并移除Update()内容:

public class BeBot_Controller  : MonoBehaviour
{
    private Animator anim;
    private string animationType;
    private string[] split;
    private int arrayLength;

    void Start ()
    {
        //AndroidJavaClass pluginClass = new AndroidJavaClass("yenettaapp.my_bebot_plugin.My_BeBot_Plugin");
        //animationType = pluginClass.CallStatic<string>("getMessage");
        animationType = "Null,Boxing,Backflip";
        split = animationType.Split(',');
        anim = gameObject.GetComponentInChildren<Animator>();
        arrayLength = split.Length;

        // Call here
        StartCoroutine(LoopThroughAnimation());
    }

    IEnumerator LoopThroughAnimation ()
    {
        for (int i = 1; i < arrayLength; i++)
        {
            animationType = split[i];
            Debug.Log(animationType);

            //anim.SetInteger ("AnimPar", 0);
            anim.Play(animationType);

            yield return new WaitForSeconds(10);
        }
    }
}

08-18 10:26