2017-05-07 17 views
2

我有一個來自Unity的文檔頁面的示例程序,其中包含IEnumerator Start(),如下所示,但我想知道如何在同一個腳本中擁有正常的void Start()在單個腳本中同時具有IEnumerator Start()和void Start()

我也嘗試添加void Start(),但它引發了一個錯誤。然後,我試過,包括我的代碼(這是剛剛寫入到控制檯應用程序的數據路徑)雖然通過0f的延遲參數立即執行它在IEnumerator功能,但它不會打印出任何東西......

上午什麼我錯過了?對於這種情況你需要有一個IEnumerator Start(),但你還需要執行起始代碼,通常的解決方案是什麼?

/// Saves screenshots as PNG files. 
public class PNGers : MonoBehaviour 
{ 

    // Take a shot immediately. 
    IEnumerator Start() 
    { 
     yield return UploadPNG(); 
     yield return ConsoleMSG(); 
    } 

    IEnumerator UploadPNG() 
    { 
     // We should only read the screen buffer after frame rendering is complete. 
     yield return new WaitForEndOfFrame(); 

     // Create a texture the size of the screen, with RGB24 format. 
     int width = Screen.width; 
     int height = Screen.height; 
     Texture2D tex = new Texture2D(width, height, TextureFormat.RGB24, false); 

     // Read the screen contents into the texture. 
     tex.ReadPixels(new Rect(0, 0, width, height), 0, 0); 
     tex.Apply(); 

     // Encode the texture into PNG format. 
     byte[] bytes = tex.EncodeToPNG(); 
     Object.Destroy(tex); 

     // For testing purposes, also write to a file in the project folder: 
     File.WriteAllBytes(Application.dataPath + "/../SavedScreen.png", bytes); 

    } 

    IEnumerator ConsoleMSG() 
    { 
     yield return new WaitForSeconds(0f); 
     Debug.Log(Application.dataPath); 
    } 
} 

回答

6

我有統一的文檔頁面的示例程序包含 一個IEnumerator開始(),如下圖所示,但我不知道我怎麼也能有 正常無效的start()在同一個腳本?

不能

這是因爲您不能擁有兩個具有相同名稱的函數。例外是當函數具有不同的參數類型時。我知道一個Start函數是void返回類型,而另一個是IEnumerator返回類型。這在C#中並不重要。重要的是兩個函數的參數。

在這種情況下,他們都採取任何參數,所以你不能超載them.You可以閱讀更多關於這個here

即使您使void Start函數接受參數,而IEnumerator Start函數也不接受參數,它將不起作用。例如,

void Start(int i) 
{ 
    Debug.Log("Hello Log 1"); 
} 

IEnumerator Start() 
{ 
    yield return null; 
    Debug.Log("Hello Log 2"); 
} 

統一將引發兩種編譯(編輯)和運行時異常:

Script error (<ScriptName>): Start() can not take parameters.


如果您切換它,使void Start沒有任何參數,但IEnumerator帶參數,它將編譯和你不會得到任何錯誤,但當你運行/玩你的遊戲IEnumerator Start函數將不會被調用。

void Start() 
{ 
    Debug.Log("Hello Log 1"); 
} 

IEnumerator Start(int i) 
{ 
    yield return null; 
    Debug.Log("Hello Log 2"); 
} 

什麼是通常的解決方案,你必須有 一個IEnumerator開始(),但你還需要執行起始碼這樣的情況?

在任何其他代碼之前在IEnumerator Start函數中運行您的起始代碼。

IEnumerator Start() 
{ 
    //Run your Starting code 
    startingCode(); 

    //Run Other coroutine functions 
    yield return UploadPNG(); 
    yield return ConsoleMSG(); 
} 

IEnumerator UploadPNG() 
{ 

} 

IEnumerator ConsoleMSG() 
{ 
    yield return new WaitForSeconds(0f); 
} 

void startingCode() 
{ 
    //Yourstarting code 
} 

,您還可以在void Awake()void Enable()函數執行起始碼。

+1

非常感謝你提供瞭如此詳細和翔實的答案。 – Joshua

+0

不客氣! – Programmer