我有一个Unity c#脚本,用于ping服务器,直到服务器端的变量从false变为true。我想要一个"循环功能"这将每隔4秒ping我的服务器以检查服务器端变量是否已更改。出于某种原因,我无法弄清楚这一点(我是c#的新手)。任何人都可以帮我设置一个功能,每四秒钟ping一次URL,然后成功"成功"做点什么?
void PendingGUI (int windowID){
GUI.Box(new Rect(0,0,Screen.width, Screen.height), "");
if(GUI.Button(new Rect(Screen.width/2 - 150, 4* Screen.height/6, 300, Screen.height/8), "Pending Mode"))
{
StartCoroutine("PendingMode");
currentMenu = "PendingMode";
Debug.Log("Pending Connection");
}
GUI.Label(new Rect(Screen.width/2 - 50, 32 * Screen.height/100, 200, 30), "Login Successful!");
GUI.Label(new Rect(Screen.width/4 + 75, 32 * Screen.height/70, 300, Screen.height/8), "Click the Pending Mode Button.");
}
void PendingModeGUI (int windowID){
if(PendingStatus == "disabled"){
StartCoroutine("PingAgain");
}
GUI.Box(new Rect(0,0,Screen.width, Screen.height), "");
GUI.Label(new Rect(Screen.width/4 + 150, 32 * Screen.height/70, 300, Screen.height/8), "Connection Pending...");
}
#region CoRoutines
IEnumerator PendingMode(){
WWWForm Ping = new WWWForm ();
Ping.AddField ("ClassPending", "ping");
WWW PingWWW = new WWW ("http://learn.edupal.co/login.php?action=classroom", Ping);
yield return PingWWW;
if (PingWWW.error != null) {
Debug.LogError ("Cannot Connect to Server");
} else {
string PingReturn = PingWWW.text;
if (PingReturn == "Success") {
Debug.Log ("Connected to Instructor");
PendingStatus = "enabled";
currentMenu = "connected";
} else {
Debug.Log (PingReturn);
PendingStatus = "disabled";
}
}
}
IEnumerator PingAgain(){
while (PendingStatus == "disabled") {
yield return new WaitForSeconds (4);
StartCoroutine ("PendingMode");
}
}
#endregion
现在的问题是循环每秒运行36次然后使游戏崩溃。我创建了字符串
PendingStatus = "disabled";
作为打破一个循环的触发器,但我也没有成功。
答案 0 :(得分:1)
我打赌你不止一次开始PingAgain
。
从您的示例中不清楚谁在调用PendingModeGUI
,但我假设它来自某OnGUI
的{{1}}方法。
只需一个Coroutine即可实现您想要的效果。 MonoBeahviour
可以更改如下:
PendingMode
注意:这实际上并不是每4秒对服务器执行一次ping操作,它会在4秒后对服务器进行ping操作+获取响应的时间。