- Home /
Yield WaitForSeconds Not causing any pause
I'm trying to make a conversation in my game. To do this I need there to be a pause between the dialogue changes. I tried using yield WaitForSeconds(5); but I got an error. After much research and use of IENumerators, I do not get an error, but it doesn't cause a pause either.
This is my code
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Couple") {
couple.text = "Who are you?";
StartCoroutine(Wait ());
me.text = ".....";
}
}
IEnumerator Wait()
{
Debug.Log ("waiting");
yield return new WaitForSeconds(10);
Debug.Log ("Time's UP!");
}
The Debug.log returns the "Waiting" but never calls the "Time Up!". I'm really confused :(
Answer by Eric5h5 · Mar 01, 2014 at 05:50 PM
I'd guess you're destroying the object before the 10 seconds are up, so the script doesn't exist anymore.
Destroying it? But the "..." does appear. There is simply no wait time in between.
Nor should there be any wait, since you're setting the text to "....." immediately. If the "Time's up" is never printed I have to assume the script is being removed or disabled.
well what exactly could be disabling it? I feel like I must be misunderstanding something fundamental about WaitForSeconds. I thought that when I call Wait() in between the lines of Dialogue, it would pause before going on to the next line. Also, where would I be disabling the script? Wouldn't it be in the lines I printed somewhere?
You're not yielding on the coroutine, you're just starting it. https://docs.unity3d.com/Documentation/ScriptReference/$$anonymous$$onoBehaviour.StartCoroutine.html
Answer by RabidCabbage · Nov 20, 2014 at 09:41 AM
Startcoroutine creates a new thread (kinda) that runs alongside the current code, it does not halt progression in the main code, only inside the separate Wait function.
If you want something to happen after some time, than it needs to be placed inside the Wait function after the yield.
I can only assume that either:
The "Time's UP!" would be printed after 10 seconds, but you are confused by the instant "....." and not waiting the 10 seconds afterwards.
Or as others have said, the script is being destroyed before the 10 seconds are up.
Try:
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.tag == "Couple") {
couple.text = "Who are you?";
// The 2 arg's are a bonus suggestion to make Wait() reusable and are
// not needed to function, I just have OCD for these things. sorry!
StartCoroutine (Wait (10, "....."));
}
}
IEnumerator Wait(int delay, string response)
{
Debug.Log ("waiting");
yield return new WaitForSeconds(delay);
Debug.Log ("Time's UP!");
me.text = response;
}
PS. This code made me think of a game I've been playing recently called "This War of Mine". Have you been playing it too? :)