- Home /
Flashlight Battery Help
Hello!
I am creating a flashlight with batterys and I got some problems. When the flashlight is off nothing happends and when I activate it again, it goes down only like 0.05 on the battery life. Also when I reach 0 it goes to -.
Here is my code: Flashlight (C#)
using UnityEngine;
using System.Collections;
public class Flashlight : MonoBehaviour {
private bool FlashlightOn = true;
public AudioClip clickOn;
public AudioClip clickOff;
public static float BatteryLife = 1;
public float BatteryReductionSpeed = 3.0f;
private float BatteryReductionSpeedOff = 0.0f;
public float onIntensity = 3.0f;
// Use this for initialization
void Start () {
light.intensity = onIntensity;
}
// Update is called once per frame
void Update () {
if(Input.GetButtonDown("Toggle Flashlight") && FlashlightOn == false){
FlashlightOn = true;
light.intensity = onIntensity;
audio.PlayOneShot (clickOn);
BatteryLife = BatteryLife - (BatteryReductionSpeed * Time.deltaTime);
if(BatteryLife <= 0 && FlashlightHud.BatteryCount > 0)
{
FlashlightHud.BatteryCount --;
BatteryLife = 100;
}
}
else if(Input.GetButtonDown ("Toggle Flashlight") && FlashlightOn == true) {
FlashlightOn = false;
light.intensity = 0;
audio.PlayOneShot (clickOff);
BatteryLife = BatteryLife - (BatteryReductionSpeedOff * Time.deltaTime);
}
}
}
FlashLightHud: (C#)
using UnityEngine;
using System.Collections;
public class FlashlightHud : MonoBehaviour
{
public static int BatteryCount;
void OnGUI()
{
GUI.Label(new Rect(10,10,80,30), "Flashlight:" );
GUI.Label(new Rect(70,10,80,30), Flashlight.BatteryLife.ToString("F2"));
GUI.Label(new Rect(10, 30, 80, 30), "Batteries:");
GUI.Label(new Rect(70, 30, 80, 30), BatteryCount.ToString());
}
}
Thanks!
Looks to me like your update function will only decrement your battery if you have clicked the on or off for the flashlight. If you never click it, then there isn't a case in the update that will decrement the battery over time.
Just as a small coding tip:
Doing BooleanVariable == True
is the same as just BooleanVariable
.
For BooleanVariable == False
it is the same as just !BooleanVariable
Writing any more will just make for more confusing/untidy code
harko is right I think. Separate the logic for turning the light on and off from the logic for depleting the battery and you'll make the problem much easier to see.