如何在其他协同开始之前先完成协程

时间:2014-11-04 04:36:26

标签: c# unity3d coroutine

嗨,我是团结新手和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 ();
 }

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

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

1 个答案:

答案 0 :(得分: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());
}

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

相关问题