- Home /
yield WaitForSeconds c#
How does yield WaitForSeconds work in c#?
i've tried, but I can't seem to make it work, and I can't find anything that helps me online!
I'm making a game, where when I look at a certain object, and the distance between me and the object is less than 2 I wan't to do something. But only after, like 5 seconds. So I need the WaitForSeconds function. Please help me!!!
When I use invoke, it calls the function inside it, for example print("SO$$anonymous$$ETHING");, like 17 times!
Answer by gjf · Aug 11, 2014 at 04:47 PM
Invoke("functionName", 5.0f);
will invoke a function called functionName
after 5 seconds...
using Invoke() is so much better than waiting and coroutines. It also works consistently the same way in JS and C#. I found about this from somewhere else but some stumbled upon this again and wanted to say thank you :)
gjf, This is a couple years old but thank you very much! I prefer your solution over using a coroutine. Thank you very much!
Answer by Wuzseen · Aug 11, 2014 at 05:01 PM
As gjf stated, you could use invoke.
yield waitforseconds, however, is something you use inside a coroutine.
A coroutine is a block of code that executes on its own time frame. IE. not in Update/FixedUpdate/Etc.
IEnumerator ExecuteAfterTime(float time) {
// stuff
yield return new WaitForSeconds(time); // the program waits time seconds before continuing
// more stuff
}
A coroutine is often used to make code that "blocks" while waiting for a condition to be true. Another good example is a spawning system where you want an item to spawn continuously, every X seconds:
IEnumerator SpawnPrefabContinuously() {
while(true) {
yield return new WaitForSeconds(spawnTime);
SpawnPrefab();
}
}
Another common yield statement is: yield return null doing this causes the coroutine to pause a single frame. You can then make alternate update blocks using this method. Some people never use update and just use a coroutine (though this isn't always proper either).
It lets you separate time dependent code into separate code chunks instead of having a lot of branching logic inside update.
Answer by BillyForce · Aug 11, 2014 at 05:45 PM
In c# you have to use an IEnumerator. Google for it ;) or http://docs.unity3d.com/ScriptReference/MonoBehaviour.StartCoroutine.html
void Event ()
{
StartCoroutine("DoSomething");
}
IEnumerator DoSomething()
{
yield return new WaitForSeconds(5f);
print("Ok");
}
Answer by ulysses 31 · Aug 11, 2014 at 05:45 PM
Call this outside of Start() or Update()...
IEnumerator wait()
{
//Do whatever you need done here before waiting
yield return new WaitForSeconds (2f);
//do stuff after the 2 seconds
}
Call this in Update()...
StartCoroutine("wait");
Your answer
Follow this Question
Related Questions
unity3d invoke 0 Answers
Add one on local z axis 3 Answers
[CLOSED]RaycastAll Help 1 Answer
Photon enable/ disable object 2 Answers