- Home /
yield WaitForSeconds
Hello eveyone, is there any way to do if statement with yield WaitForSeconds? Like,
if(yield WaitForSeconds(5)){
//do stuff here
}
I tried but it doesn't work. Any suggestions?
Thanks :)
What are you trying to accomplish? The yield
will wait, then begin executing the code after the yield
is done waiting. What are you trying to accomplish with the if
?
Don't think yield can be used like that no. WaitForSeconds can only be used with a yield statement in coroutines.
Have a look at this great earlier answer for a nice description of how to use yield waitForSeconds :)
http://answers.unity3d.com/questions/350721/c-yield-waitforseconds.html
$$anonymous$$y code is this:
function OnTriggerEnter (col : Collider){
if(col.gameObject.tag=="Player"){
var mesh : $$anonymous$$esh = GetComponent($$anonymous$$eshFilter).mesh;
mesh.Clear();
collider.enabled = false;
audio.Play();
yield WaitForSeconds(1);
Invetory.inventoryArray[0]++;
Destroy(gameObject);
}
}
This is when the player hits this cude, it adds 1 health potion to his invetory after 1 second
So, I tried to hack my game with Cheat Engine [add more health potions] and it works. I want to say that if a potion added in less than one second then remove it. Any suggestions?
I think Dimling is right, you have to use it in a coroutine. Ex:
function OnTriggerEnter (col : Collider){
if(col.gameObject.tag=="Player"){
var mesh : $$anonymous$$esh = GetComponent($$anonymous$$eshFilter).mesh;
mesh.Clear();
collider.enabled = false;
audio.Play();
StartCoroutine(WaitAndDo(1));
}
}
function WaitAndDo (waitTime : float) {
// suspend execution for waitTime seconds
yield WaitForSeconds (waitTime);
Invetory.inventoryArray[0]++;
Destroy(gameObject);
}
Does this suits you ?
Answer by Jamora · Jul 24, 2013 at 12:57 PM
You should just remember the amount of potions in the inventory before the wait and check if it's the same afterwards. Now, if there are other, allowed, ways of getting potions you will have to update my numberOfPotions accordingly, because this script doesn't discriminate.
Basic idea:
function OnTriggerEnter (col : Collider){
if(col.gameObject.tag=="Player"){
int numberOfPotions = Invetory.inventoryArray[0];
yield WaitForSeconds(1f);
if(Invetory.inventoryArray[0] > numberOfPotions){
//Player has cheated... possibly.
Invetory.inventoryArray[0] = numberOfPotions;
}else{
Invetory.inventoryArray[0]++;
Destroy(gameObject);
}
}
}
int and 1f are both C# only (should be var and 1). Otherwise this solution is correct.
Your answer
Follow this Question
Related Questions
How does Invoke cope with mapping on frames 1 Answer
Increase variable for a few seconds 2 Answers
Temporarily disable blayer movement? 1 Answer
What is the most CPU efficient and smooth way to create timed events? 2 Answers
Waitforseconds vs Time 2 Answers