I’ve been trying to implement a Stamina system to my Sprint Script (JavaScript) but for some reason it causes my game to crash. I’ve pinpointed two instances that causes it to crash:
- In the following lines of code:
while (stamina < 100)//if stamina is less than 100% { while (walking)//when walking { stamina = stamina + 0.25 * Time.deltaTime;//stamina increases at 1/4th the rate it depletes } }
Whenever I try to sprint, Unity crashes.
- If the block above is commented out, in the following lines of code:
switch (stamina) { case 0://if stamina fully depletes recover = true;//recovery mode is enabled break; } if (recover)//if in recovery mode { while (stamina < 25)//while stamina is less than 25% { speed = walkSpd;//walking speed is the max speed if (stamina >= 25)//if stamina is equal to or greater than 25% { recover = false;//recovery mode is disabled } } }
Unity crashes when Stamina reaches zero.
Here is my entire script:
#pragma strict private var walkSpd : float = 4; //Walking speed value private var jogSpd : float = 6; //Jogging speed value private var charMotor : CharacterMotor; private var charController : CharacterController; var stamina : int; private var recover : boolean; private var walking : boolean; function Start () { charMotor = GetComponent(CharacterMotor); charController = GetComponent(CharacterController); stamina = 100; recover = false; walking = true; } function Update () { var speed = walkSpd;//sets default speed to walking speed if (charController.isGrounded && Input.GetKey(KeyCode.LeftShift) || charController.isGrounded && Input.GetKey(KeyCode.RightShift)) { //if the player's character is on the ground AND he/she is pressing a SHIFT key speed = jogSpd; //the player moves at jogging speed stamina = stamina - 1 * Time.deltaTime; //stamina decreases over time walking = false; //the player is not walking } else //if the player is NOT on the ground AND holding a SHIFT key { /*speed = walkSpd;*/ //the player's speed is walking speed walking = true; //the player is walking } switch (stamina) { case 0://if stamina fully depletes recover = true;//recovery mode is enabled break; } if (recover)//if in recovery mode { while (stamina < 25)//while stamina is less than 25% { speed = walkSpd;//walking speed is the max speed if (stamina >= 25)//if stamina is equal to or greater than 25% { recover = false;//recovery mode is disabled } } } while (stamina < 100)//if stamina is less than 100% { while (walking)//when walking { stamina = stamina + 0.25 * Time.deltaTime;//stamina increases at 1/4th the rate it depletes } } charMotor.movement.maxForwardSpeed = speed; //Setting new speed variable under appropriate conditions }
What am I doing wrong?