- Home /
Problems with yield WaitForSeconds(); (IENumerator)
Hello, my prob is the next: I have a script that helps met to cut trees. I only got a problem with this. Because my IENumerator doesn't seem to be working. With the first tree my script works well. But if you immediately start with cutting down another tree after the first one, you cut it down in 0 seconds. And that is not what I want.... So please take a look at my script and explain me what I'm doing wrong.
if(isWoodCutting == true){//iswoodcutting gets true by means of another script isWoodCutting = false; StartCoroutine(WaitForTreeFall()); } //if a tree is cut down if(treeDown == true){ treeDown = false; Destroy(target); } } IEnumerator WaitForTreeFall(){ yield return new WaitForSeconds(10);//this sometimes seems to be ignored... if(target != null){ treeDown = true; } yield break; }
I don't think this is your problem area. Are you sure isWoodCutting is not being set back to true by the other script before you start 'cutting'?
Answer by Minizinger · Nov 28, 2013 at 04:41 PM
Looks like the problem is: you use one boolean treeDown for whole script. So when you starting function second time it gets treeDown from 1st time. I'd better use something like this:
bool isWoodCutting;
bool cuttingTreeNow;
float cooldown;
void Update(){
if(isWoodCutting && !cuttingTreeNow){
cooldown = 10;
cuttingTreeNow = true;
}
if(cooldown > 0)
cooldown -= Time.deltaTime; //-1 per second
if(cooldown <= 0 && cuttingTreeNow){
cuttingTreeNow = false;
Destroy(target);
}
}
Oh and don't forget to set isWoodCutting to false somewhere
Thank you for responding but I can't understand why my IENumerator is'nt working. I truly believe my booleans work fine. However your way will be working as well. :)
Atleast, ins$$anonymous$$d of using treeDown boolean, try to Destroy your target exactly in IEnumerator, this should work. But if you don't want allow player cutting 2,3,4 and more trees at same time, you better use cooldowns.
Your answer
