- Home /
How wait few second in c#
Hi, i want to make an easy menu, i wrote this:
void Update () {
StartCoroutine("wait");
// other
}
IEnumerator wait(){
yield return new WaitForSeconds(5.0f);
}
it doesn't work, it doesn't wait... D: What it goes wrong ?
Answer by whydoidoit · Apr 03, 2014 at 06:49 PM
You need to do something after the coroutine - "//other" needs to be inside the coroutine
You can also use a closure to do that like this:
IEnumerator WaitThenDo(System.Action thingToDo) {
yield return new WaitForSeconds(5);
thingToDo();
}
StartCoroutine(Wait(()=>{
//other
})
StartCoroutine (WaitThenDo(()=>{ move = this.transform.position; if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.DownArrow)) { pos = (pos+1)%2;
move.x = scelteX;
move.z =scelteZ[pos];
}
else if(Input.Get$$anonymous$$ey($$anonymous$$eyCode.UpArrow))
{
if(pos == 0)
pos = 1;
else pos--;
move.x = scelteX;
move.z = scelteZ[pos];
}
else if(Input.Get$$anonymous$$eyUp($$anonymous$$eyCode.Space))
{
if(pos == 0)
Application.LoadLevel("Scene");
else if(pos == 1)
Application.Quit();
}
this.transform.position = move;
}));
IEnumerator WaitThenDo(System.Action thingToDo) {
yield return new WaitForSeconds(5);
thingToDo();
}
This ? It doesn't work..
Well it wouldn't, you'd have to release or press the key at exactly the right moment for that to do anything...
If you're deter$$anonymous$$ed to use a timed function from Update, you could do
void Update()
{
if (!IsInvoking("$$anonymous$$ethodToRun"))
{
Invoke("$$anonymous$$ethodToRun", 5f);
}
}
void $$anonymous$$ethodToRun()
{
// Do stuff.
}
Off the top of my head $$anonymous$$d you.
Answer by KittyKatKat · Apr 03, 2014 at 07:04 PM
Your process should be put inside the IEnumerator, not below StartCoroutine. The system starts the coroutine (the IEnumerator function), but carries on doing its task. But what's below the line "yield return new WaitForSeconds(5f);" is what will happen after those 5 seconds.
void Update(){
StartCoroutine("wait");
}
IEnumerator wait(){
while(true){
yield return new WaitForSeconds(5.0f);
//stuff
}
}
I haven't tested and I'm still a learner my self, but I think this will work, since while loop will happen infinately (true is always true) - or if you want an ending condition, replace it with the true part in while (as a parameter).
Test this out, see if it works.
Your answer
Follow this Question
Related Questions
WaitForSecondsRealtime Progressively out of Sync... Unity 1 Answer
Waiting then Executing 4 Answers
Sequentially wait for multiple coroutines to finish 0 Answers
Wierd issue with Coroutines? 2 Answers
Wait until animation is finished 2 Answers