在Unity中使用Coroutine

时间:2018-04-12 05:06:46

标签: c# android arrays unity3d

我正在使用Unity,这就是我想要做的事情:以10秒的时差播放 animationType 。我希望代码循环播放动画并每次播放它们10秒。代码运行没有错误,除了结果不是我预期的结果。它播放第一个动画,拳击,持续10秒,当它即将播放 Backflip 动画时,它开始对角色做一些奇怪的事情。这就是出错的地方。

这是我的代码:

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);
        }
    }
}

那我在这里做错了什么?还有其他方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:1)

由于您的动画循环只需要调用一次,只需将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);
        }
    }
}