【问题标题】:Using Coroutine in Unity在 Unity 中使用协程
【发布时间】:2018-04-12 05:06:45
【问题描述】:

我正在开发 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);
        }
    }
}

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

【问题讨论】:

  • 您需要在该课程中发布完整的代码。这还不足以帮助您。
  • Coroutine inside Loop inside Update function,一定很麻烦。但是,for 循环的右括号不见了。

标签: c# android arrays unity3d


【解决方案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);
        }
    }
}

【讨论】:

  • 它工作得很好。但是我们需要 Update 方法来做什么?
  • @NathanDamtew Update 用于每帧行为。见Update And FixedUpdate :)
  • 是的。谢谢@Lece
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 2021-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-12
相关资源
最近更新 更多