问题
Look at this simple code:
function Start()
{
yield WaitForSeconds (4);
Application.LoadLevel(1);
}
It works! I'm trying to make something similiar using C#, but the processor just ignore the WaitForSeconds. This is my code in C#:
using UnityEngine;
using System.Collections;
public class openingC : MonoBehaviour
{
void Start()
{
executeWait(5);
Application.LoadLevel(1);
}
void executeWait(float aux)
{
StartCoroutine(Wait(aux));
}
IEnumerator Wait(float seconds)
{
yield return new WaitForSeconds(seconds);
}
}
Can someone explain to me why it's not working? Thanks for your time.
回答1:
public class openingC : MonoBehaviour
{
void Start()
{
executeWait(5);
Application.LoadLevel(1);
}
void executeWait(float aux)
{
StartCoroutine(Wait(aux));
}
IEnumerator Wait(float seconds)
{
yield return new WaitForSeconds(seconds);
}
}
First, the Start method runs, executeWait is called, the program jumps to the method. It finds the coroutine and starts running it until a yield is found or the end of the method. Yield returns to the program, the pointer goes back up to executeWait and finishes the method. The pointer goes back up to Start and calls for Application.LoadLevel.
You want to hang the LoadLevel call.
public class openingC : MonoBehaviour
{
void Start()
{
StartCoroutine(Wait(5));
}
//You don't need executeWait
IEnumerator Wait(float seconds)
{
yield return new WaitForSeconds(seconds);
Application.LoadLevel(1);
}
}
回答2:
Try this:
Thread.Sleep(500); //500 millisecond waiting...
Reference
回答3:
This should also be okay.
IEnumerator Start()
{
yield return new WaitForSeconds(4);
Application.LoadLevel (1);
}
来源:https://stackoverflow.com/questions/34242353/waitforseconds-on-c-sharp