c# - 在 Unity 中使用协程

标签 c# android arrays unity3d

我正在使用 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);
        }
    }
}

关于c# - 在 Unity 中使用协程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49788402/

相关文章:

c++ - 可以在不使用数组的情况下对字符串变量的内容进行排序吗?

将对象转换为数组的 PHP 错误

java - 如何通过按下按钮从 android 程序堆栈中删除除第一个项目之外的所有项目?

java - 数组复制困惑

c# - 如何将跟踪/异常数据从控制台 C# 应用程序获取到 Application Insights

c# - Visual Studio 2022 关闭自动缩进

android - 当用户在 Google Maps v2 for Android API 上按下“我的位置中心”按钮时如何收到通知

android - 等级错误:找不到ID为 'com.android.model.application'的插件

c# - 按公共(public)属性对不同对象的列表进行排序

c# - 如何返回具有通用属性的 C# Web 服务?