Jos*_*hua 2 c# unity-game-engine
我有一个来自Unity文档页面的示例程序,其中包含IEnumerator Start()如下所示,但我想知道如何void Start()在同一个脚本中也能正常运行?
我也尝试添加void Start()它,但它引发了一个错误.然后,我试着在一个IEnumerator函数中包含我的代码(它只是写入控制应用程序的数据路径),虽然通过使用0f延迟参数立即执行它,但它不会打印出任何东西......
我错过了什么?这种情况的常见解决方案是什么,你必须有一个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);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个来自Unity文档页面的示例程序,其中包含一个IEnumerator Start(),如下所示,但我想知道如何在同一个脚本中也有一个正常的void Start()?
你不能.
这是因为您不能拥有两个具有相同名称的函数.例外是函数具有不同的参数类型.我知道一个Start函数是void返回类型,而另一个函数是IEnumerator返回类型.这在C#中无关紧要.重要的是两个函数的参数.
在这种情况下,他们都不会采取任何争论,因此你不能超载它们.你可以在这里阅读更多相关信息.
即使您使该void Start函数采用参数而该IEnumerator Start函数不采用参数,它也不起作用.例如,
void Start(int i)
{
Debug.Log("Hello Log 1");
}
Run Code Online (Sandbox Code Playgroud)
和
IEnumerator Start()
{
yield return null;
Debug.Log("Hello Log 2");
}
Run Code Online (Sandbox Code Playgroud)
Unity将抛出编译(Editor)和运行时异常:
Script error (<ScriptName>): Start() can not take parameters.
如果你切换它并且void Start没有任何参数但是IEnumerator 带有参数,它将编译并且你不会得到任何错误但是IEnumerator Start当你运行/玩游戏时不会调用该函数.
void Start()
{
Debug.Log("Hello Log 1");
}
Run Code Online (Sandbox Code Playgroud)
和
IEnumerator Start(int i)
{
yield return null;
Debug.Log("Hello Log 2");
}
Run Code Online (Sandbox Code Playgroud)
对于你必须拥有IEnumerator Start()但你还需要执行启动代码的情况,通常的解决方案是什么?
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
}
Run Code Online (Sandbox Code Playgroud)
您还可以在void Awake()或void Enable()函数中执行启动代码.
| 归档时间: |
|
| 查看次数: |
1202 次 |
| 最近记录: |