How can I stop an int from adding with the getkeydown
When I collect a battery it goes into the int Battery Count. When the current battery power reaches 0 and the battery count is greater than 0 the battery count reduces and current battery power increases 100%. That works. But what I want is for when the current battery power reduces to 50% I want to press the "T" key and use one of the Battery Count and increase back to 100%. What happens is that I can continue press "T" and the count goes into a negative number and the Current battery power goes to 100% instead of ending at 0 battery counts and 0 % current battery Power. I know I need an ELSE in the script but there is where I get in trouble with it. Part of the script is below.
public float _currantBatteryPower = 0f; public static int BatteryCount; void Update(){
if (_currantBatteryPower <= 0 && BatteryCount > 0)
{
BatteryCount--;
_currantBatteryPower = 100;
} if (Input.GetKeyDown(KeyCode.T) && _currantBatteryPower <= 50 ) {
GetComponent<AudioSource>().PlayOneShot(_PickupSound);
BatteryCount--;
_currantBatteryPower = 100;
}
Answer by Suddoha · Oct 04, 2015 at 12:28 PM
You can either add another condition to the second if statement like
if (Input.GetKeyDown(KeyCode.T) && _currantBatteryPower <= 50 && BatteryCount > 0)
or you avoid redundant code and do it like this, for example:
public float _currentBatteryPower = 0f;
public static int BatteryCount;
void Update()
{
UseBattery(0f);
if (Input.GetKeyDown(KeyCode.T))
UseBattery(50f);
}
private void UseBattery(float threshold)
{
if (_currentBatteryPower <= threshold && BatteryCount > 0)
{
BatteryCount--;
_currentBatteryPower = 100;
}
}
(i renamed currantBatteryPower to currentBatteryPower with e, either change it again or make sure the other scripts use the same name)
Answer by dbknights2000 · Oct 04, 2015 at 01:31 PM
Thank You, Thank You, this was driving me batty, and now I can relax and play Bat Man this fine Sunday Morning.