【问题标题】:how to make a coroutine finish first before other coroutine start如何在其他协程开始之前先完成协程
【发布时间】:2014-12-30 21:54:28
【问题描述】:

嗨,我是 Unity 和 c# 的新手..

我在同一个场景中有两个脚本文件,

文件 versionchecker.cs 中的 1 个协程,用于从我的 Web 服务器获取版本号数据

public string versionURL = "http://localhost/check.php";

 IEnumerator GetVersion()
 {
     WWW vs_get = new WWW(versionURL);
     yield return vs_get;

     if (vs_get.error != null)
     {
         connection = 1;
     }
     else
     {
         currentVersion = vs_get.text;
         bundleVersion = PlayerSettings.bundleVersion;
         connection = 0;
     }
 }

但是在 beginingscreen.cs 的另一个文件中,我有一个用于起始屏幕的协程..

 void Start () {
     if(!isExit)
         StartCoroutine (BeginningAnimation ());
     else
         StartCoroutine (EndAnimation ());
 }

 IEnumerator BeginningAnimation()
 {
     fade.FadeIn (1.5f);
     yield return new WaitForSeconds (2);
     fade.FadeOut (1);
     yield return new WaitForSeconds (0.9f);
     Application.LoadLevel (LevelToLoad);
 }

 IEnumerator EndAnimation()
 {
     yield return new WaitForSeconds (0.5f);
     fade.FadeOut (1);
     yield return new WaitForSeconds (1);
     Application.Quit ();
 }

这个脚本我把它放在我游戏的同一个场景中。但有时开始屏幕的协程在获取版本的协程之前先完成,因为获取版本需要连接到网络服务器,有时网络服务器滞后。 .

那么我怎样才能让获取版本协程首先完成,然后开始屏幕才能启动..

【问题讨论】:

  • 在第二个协程中使用yield return WaitUntil(() => coroutineOver);,其中coroutineOver是一个bool,一旦第一个协程结束就设置为true。

标签: c# unity3d coroutine


【解决方案1】:

两种不同的方法:

您可以仅在第一个协程执行完毕后添加组件脚本(beginingscreen.cs)。从而确保其他协程不会启动得太早。

IEnumerator GetVersion()
{
    // ...
    gameObject.AddComponent<BeginingScreen>();
}

您可以在beginingscreen.cs 中将Start 方法设为协程,然后调用GetVersion 并等待其完成(GetVersion 需要公开可见):

IEnumerator Start()
{
    var getVersion = gameObject.GetComponent<VersionChecker>();
    if (getVersion != null)
    {
        yield return StartCoroutine(getVersion.GetVersion());
    }

    if(!isExit)
        yield return StartCoroutine (BeginningAnimation());
    else
        yield return StartCoroutine (EndAnimation());
}

在这两种解决方案中,您都需要两个组件(脚本)以某种方式相互交互。或者,您可以创建第三个脚本来处理此交互。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-07
    • 2018-10-29
    • 2021-10-24
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多