"If statement" and whiled loop acting strange and crashes
I'm trying to make a charge up but It doesn't want to work for some reason. What I want is when "k" is held now, the value of chargeTime is increased until the person lets go of "k" or it reaches 15 which is the max I want it to go. Here is my code:
public float chargeTime = 0f;
public float maxChargeTime = 15f;
void FixedUpdate() {
ChargeTimeF();
}
void ChargeTimeF(){
while(Input.GetKey("k")){
chargeTime += Time.fixedDeltaTime * 2;
if (chargeTime > maxChargeTime) {
break;
}
}
}
When I run the code above, instead of chargeTime starting at zero and then going up from there. It starts with whatever the value of maxChargeTime is and goes to infinity, completely passing the if-statement condition. Into more testing, I changed a few things out and found out if I change the if-statement to (chargeTime < maxChargeTime) and this does exactly what I wanted. It starts at zero but when it gets near the value of maxChargeTime it crashes the engine.
I hope anyone can help I feel so stupid because I feel like it's so simple yet I have no idea what's wrong with it. I understand C++ really well and I don't think that C# was that different. What am I missing or doing wrong??
Answer by Larry-Dietz · Dec 16, 2019 at 02:17 AM
First thing to do is move your increment to after your if block. As it stand now, it will break out of the while, but in the very next fixed update cycle, it will increment again, beyond your max, then the if will break it out again, but again on the next cycle it increments again, and so on and so on...
After making this change, if there are still issues, let me know.
Hope this helps, -Larry
void ChargeTimeF(){
while(Input.Get$$anonymous$$ey("k")){
if (chargeTime > maxChargeTime) {
break;
}
chargeTime += Time.fixedDeltaTime * 2;
}
}
Okay, I hope this is what you wanted me to do. The chargeTime instantly becomes 15.0009 and stops there the moment I press "k". That's what I can't figure out, it instantly goes to whatever the max is. I changed the maxChargeTime to 100 and get 100.0322 as the chargeTime when I press "k". Ins$$anonymous$$d of "time.fixedDeltaTime" should I use something else?
Ok, figured it out.
You are using a while loop, inside the update method. So, when you kit the $$anonymous$$, the getkey stays true during that entire cycle, and loops until it surpasses your max.
Change to this, and it should work as you expect.
void ChargeTimeF()
{
if (Input.Get$$anonymous$$ey($$anonymous$$eyCode.$$anonymous$$))
{
if (chargeTime > maxChargeTime)
{
return;
}
chargeTime += Time.fixedDeltaTime * 2;
}
}
Thank you, this worked. Larry you the man!