1
我有一個Unity c#腳本,旨在ping服務器,直到服務器端的變量從false變爲true。我想要一個「循環函數」,它會每4秒鐘檢測一次服務器端變量是否發生變化。出於某種原因,我無法弄清楚(我是C#的新手)。任何人都可以幫助我設置一個功能,每四秒鐘ping一個URL,並在「成功」做些什麼?Unity3D保持ping服務器直到真
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";
作爲一個觸發器來打破一個while循環,但是我沒有成功。
是的,我正在使用Monobehaviour。我實現了你的代碼,它每秒鐘處理大約500次的服務器。我移動了StartCoroutine(「PendingMode」);刪除PendingModeGUI並刪除if語句。如果沒有PendingModeGUI中的StartCoroutine,它只會觸發一次,然後停止。 –
得到它的工作!謝謝 :) –