- Home /
Wait For Seconds c#
i know that was asked a lot of times from other users, but i still can use wait for seconds on c#,
i have this:
if(Input.GetKeyDown(KeyCode.Q)) {
if(GetComponentInChildren<WeaponBase>().isAiming) {
GetComponentInChildren<WeaponBase>().AimOut();
yield return new WaitForSeconds(3.0f);
SwitchWeapon();
}
else {
SwitchWeapon();
}
}
i know that i need IEnumerator but i can't put it on the code. someone can help me ?
To call a Coroutine:
StartCoroutine(YourCoroutine());
//or use a string
StartCoroutine("YourCoroutine");
You cannot call it by simply using:
YourCoroutine();
That would be calling as if you had:
void YourCoroutine(){}
But we are using IEnumerator here, docs I linked will help you better understand.
CLIC$$anonymous$$ HERE for more information on StartCoroutine
Answer by YoungDeveloper · Sep 07, 2013 at 06:22 PM
bool canSwitch = false;
bool waitActive = false; //so wait function wouldn't be called many times per frame
IEnumerator Wait(){
waitActive = true;
yield return new WaitForSeconds (3.0f);
canSwitch = true;
waitActive = false;
}
if(Input.GetKeyDown(KeyCode.Q)) {
if(GetComponentInChildren<WeaponBase>().isAiming) {
GetComponentInChildren<WeaponBase>().AimOut();
if(!waitActive){
StartCoroutine(Wait());
}
if(canSwitch){
SwitchWeapon();
canSwitch = false;
}
else {
SwitchWeapon();
}
}
Answer by Deniz2014 · Mar 23, 2017 at 08:18 AM
I wanted to wait x Seconds in the Update() before continuing. So if someone, like me, searched this / needs this and is now here:
private float timer = 0;
private float timerMax = 0;
void Update ()
{
text += "Allow yourself to see what you don’t allow yourself to see.";
if(!Waited(3)) return;
text += "\n\nPress any key!";
}
private bool Waited(float seconds)
{
timerMax = seconds;
timer += Time.deltaTime;
if (timer >= timerMax)
{
return true; //max reached - waited x - seconds
}
return false;
}
Answer by Deniz2014 · Mar 22, 2017 at 10:48 PM
I wanted to wait x Seconds in the Update() before continuing. So you cannot use the yield there (don't want to start a coroutine every frame right?)
So if someone, like me, searched this / needs this in and for the Update():
private float timer = 0;
private float timerMax = 0;
void Update ()
{
text += "Allow yourself to see what you don’t allow yourself to see.";
if(!Waited(3)) return;
text += "\n\nPress any key!";
}
private bool Waited(float seconds)
{
timerMax = seconds;
timer += Time.deltaTime;
if (timer >= timerMax)
{
return true; //max reached - waited x - seconds
}
return false;
}
Your answer
Follow this Question
Related Questions
Yielding in between functions... 2 Answers
Ienumerator return string 0 Answers
Corutine not behaving like it should? 1 Answer
How to use Coroutines in C++/CLI? 1 Answer