我有一個來自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);
}
}
非常感謝你提供瞭如此詳細和翔實的答案。 – Joshua
不客氣! – Programmer