如何在其他协程启动之前先完成一个协程 [英] how to make a coroutine finish first before other coroutine start
问题描述
我是 unity 和 c# 的新手..
Hi im a newbie in unity and c#..
我在同一个场景中有两个脚本文件,
I have two script file in the same scene,
文件 versionchecker.cs 中的 1 个协程以从我的网络服务器获取版本号数据
1 coroutine in file versionchecker.cs to get a version number data from my web server
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 的另一个文件中,我有一个用于开始屏幕的协程..
But in another file in beginingscreen.cs, i have a coroutine for a begining screen..
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 ();
}
这个脚本我把它放在我的游戏的同一个场景中..但有时开始屏幕的协程在获取版本的协程之前先完成,因为获取版本需要连接到网络服务器,有时网络服务器滞后..
this script i place it in the same scene of my game.. but sometimes the coroutine for begining screen finish first before the coroutine for get version because the get version need a connection to webserver, and sometime the web server is lagging..
那么我怎样才能让 get 版本协程先完成,然后开始屏幕才能启动..
so how can i make the get version coroutine finish first and after that begining screen can start..
推荐答案
两种不同的方法:
您只能在第一个协程执行完毕后才添加组件脚本(beginingscreen.cs).从而确保其他协程不会过早启动.
You could just add the component script (beginingscreen.cs) only when the first coroutine finished executing. Thus ensuring that the other coroutines do not start too early.
IEnumerator GetVersion()
{
// ...
gameObject.AddComponent<BeginingScreen>();
}
可以在 beginingscreen.cs 中将 Start 方法设为协程,然后调用 GetVersion 并等待其完成(GetVersion 需要公开可见):
You can make the Start method a coroutine in beginingscreen.cs, then call GetVersion and wait for its completion (GetVersion needs to be publicly visible) :
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());
}
在这两种解决方案中,您都需要两个组件(脚本)以某种方式相互交互.或者,您可以创建第三个脚本来处理此交互.
In both solutions, you need the two components (scripts) to somehow interact with each other. Or you can create a third script that handles this interaction.
这篇关于如何在其他协程启动之前先完成一个协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!