- Home /
c# waitforsecconds
i am pretty new to c# and after all searching and trying i still cant get yield return new waitforsecconds to work i know i need a coroutine but i just can't get it up to work. and is it possible to use waitforsecconds in void update?can someone just please give me a very clearfact about waitforsecconds in c#
ps. sorry for bad english i'm dutch.
Answer by Yatheesh-Raju390 · Apr 22, 2014 at 06:07 AM
You can call the start coroutine where you want the delay. Suppose in the below example you will wait 2 sec before printing
using UnityEngine;
using System.Collections;
public class Example : MonoBehaviour {
void Start() {
print("Starting " + Time.time);
StartCoroutine(WaitAndPrint(2.0F));
print("Before WaitAndPrint Finishes " + Time.time);
}
IEnumerator WaitAndPrint(float waitTime) {
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
}
If you call the wait for seconds in update then each time the update is called a new coroutine starts this is not good as it causes unpredictable results .If you can explain the senario what you are trying to achive it will be easy to say where you should call coroutine.
But what is i put : if(input.getkey(r)) in the void update. Is that effectet whit the fact that update gets called once a frame?
using UnityEngine;
using System.Collections;
public class Example : $$anonymous$$onoBehaviour {
void Update(){
if(Input.getkey(r)){
StartCoroutine(WaitAndPrint(2.0F));
}
}
IEnumerator WaitAndPrint(float waitTime) {
yield return new WaitForSeconds(waitTime);
print("WaitAndPrint " + Time.time);
}
}
if this is what your are saying then what happens is that once you hit the r key,From that time after 2 seconds it will print the time.
Answer by Jellezilla · Apr 21, 2014 at 11:28 AM
In C# it is done with a coroutine, like this:
StartCoroutine(Wait()); // this calls the wait method below
IEnumerator Wait() {
yield return new WaitForSeconds (3.0f);
}
Thanks. But where can i put this in? Can input it in void update void start?