- Home /
Yield everytime boolean is True (C#)
Man yield and coroutines are giving me a headache...basically I have a boostCharge, and while I'm boosting, I'm emptying the boostCharge on every frame. I also have a maxBoost which defines the maximum boost amount for the boostCharge. What I'm trying to do is yield for 5 seconds every time boostCharge is less then maxBoost and I'm not boosting anymore.
Here's my current code below:
void Update () {
// Check if boost is being used...
if (GUI_Controls.boostOn && boostCharge > 0) {
boostCharge--;
}
if (boostCharge <= 0) {
bikeEngine.boostIsOn = false;
} else {
bikeEngine.boostIsOn = true;
}
// Check if boostCharge is less then maxBoost and if boost is being used...
if (boostCharge < maxBoost && !GUI_Controls.boostOn) {
StartCoroutine (waitTime (5.0F));
}
Debug.Log(boostCharge);
}
public IEnumerator waitTime (float seconds) {
yield return new WaitForSeconds (seconds);
while (boostCharge < maxBoost) {
boostCharge++;
break;
}
}
It's working the way I want 50% of the time. Some time the charge starts to refill right away (it doesn't yield) and even when I'm actually boosting, it still tries to refill the boostCharge. Some other times, it works like I intended it to work.
I'm new to coroutines and yield, so this is confusing me. I feel like I'm close but I can't figure out what I'm doing wrong.
Answer by Skjalg · Jan 30, 2011 at 11:16 AM
You gotta remember that for every frame that boostCharge is less than max boost and you are not holding in your boost button you will start a new coroutine with that code.
So lets say you play this with a 100fps, and as soon as you stop boosting, the game will make 100 new coroutines every second. That makes 500 coroutines before you see the effect of the first one.
My guess is that your logic here is just wrong from the start :) If I were you, I'd just store the time in a local variable for when the last time you let go of the boost button was, and if the time is that local time paramater + 5 seconds, then you can start charging up again...
Thanks a lot for your help, I will try what you suggest as it seems like a better (and easier) way to achieve what I want. I'm trying to wrap my brain around coroutines but I'm having a hard time figuring them out! Now let's say I had to use a coroutine to achieve what I need, how would I change my code to make it work correctly?
Your answer
Follow this Question
Related Questions
Pause the coroutine inside a loop 1 Answer
Last item not being moved (yield problem) 0 Answers
Coroutoutine doesnt work properly. 3 Answers
Im a bit confused on a simple script 1 Answer