在Unity中使用协程

内森·丹特(Nathan Damtew)

我正在Unity上工作,这是我想做的:以10秒的时差播放animationType我希望代码循环播放动画,并分别播放10秒。该代码运行没有错误,除了结果不是我期望的那样。它会播放第一个动画Boxing 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);
        }
    }
}

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

我飞

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章