2015-07-02 73 views
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循環,但是我沒有成功。

回答

1

我敢打賭你不止一次地開始PingAgain

從你的例子不清楚誰叫PendingModeGUI,但我假設它是從OnGUI方法在一些MonoBeahviour

只需一個協程就可以實現你想要的。 PendingMode可以改變如下:

IEnumerator PendingMode() 
{ 
    while(true) 
    { 
    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"); 

     //stop the coroutine 
     StopCoroutine("PendingMode"); 
     } 
     else 
     { 
     yield return new WaitForSeconds(4f); 
     } 
    } 
    } 
} 

注:這實際上並不ping服務器每4秒,它4秒+時間得到迴應後,執行ping服務器。

+0

是的,我正在使用Monobehaviour。我實現了你的代碼,它每秒鐘處理大約500次的服務器。我移動了StartCoroutine(「PendingMode」);刪除PendingModeGUI並刪除if語句。如果沒有PendingModeGUI中的StartCoroutine,它只會觸發一次,然後停止。 –

+0

得到它的工作!謝謝 :) –