- Home /
Pause in C#
I think I'm doing this right.
IEnumerator Wait()
{
yield return new WaitForSeconds(5);
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.name=="StopBlock")
{
Storage = FindObjectOfType<PlayerMovement>().speed;
FindObjectOfType<PlayerMovement>().speed = 0;
StartCoroutine("Wait");
FindObjectOfType<PlayerMovement>().speed = Storage;
}
}
This should work but it doesn't. There is no error, it's just not stopping. I don't know why.
Don't forget to mark an answer if it worked for you, so people who end up here know what helped you.
Answer by Kciwsolb · May 10, 2018 at 02:17 PM
Hi, when you start coroutine Wait(), it will still proceed to the next line of code immediately because you do not have it doing anything before it yields control back. If you want to actually wait for some amount of time and then do your Find, you need to put that line of code IN the coroutine after your wait.
IEnumerator Wait(float Storage) //Pass in your parameter
{
yield return new WaitForSeconds(5);
FindObjectOfType<PlayerMovement>().speed = Storage;
}
Then in OnTriggerEnter2D call it this way:
StartCoroutine(Wait(Storage));
Coroutines does not run on a seperate thread, they run on the $$anonymous$$ain thread. Now when you start a coroutine the code will run normaly till a yield instruction is reached control will return to the caller. The engine keeps track of the coroutine and when the "condition" of the yield has been fulfilled the control will return on the point where it had left inside the coroutine, because it is run on the main thread the order (ti$$anonymous$$g) of the return will be according to this. It is more of pseudo threading, but quite far from it.
Bad wording on my part... I removed the thread wording. Should be more accurate now. Thanks!
Answer by Derptastic · May 10, 2018 at 02:23 PM
(Some formatting of that code for readability would be appreciated.)
Are you trying to pause the whole game? Then it's
Time.timeScale
that you want.
Your code is not quite right either. What you're doing is starting a co-routine that's waiting for itself. When you call it, the co-routine starts, waits 5 seconds before continuing itself while the rest of your code continues immediately after the call, setting the player speed back to it's original setting right after you set it to 0. That's the point of co-routines, to perform async tasks.
If you insist on keeping that logic, just put the rest of the code in the "Wait" routine as well. Your code:
IEnumerator Wait()
{
Storage = FindObjectOfType<PlayerMovement>().speed;
FindObjectOfType<PlayerMovement>().speed = 0;
yield return new WaitForSeconds(5);
FindObjectOfType<PlayerMovement>().speed = Storage;
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.gameObject.name == "StopBlock")
{
StartCoroutine("Wait");
}
}
Your answer