- Home /
How to make a GUI to show how much battery is left on Flashlight?
How to make a GUI text that shows how much battery power i have left?
//Name this script Flashlight and attach it to your player for instance
var lightSource : Light; //Connect the light source in the Inspector
static var energy : float = 100; //The energy amount of the flashlight
static var turnedOn : boolean = false; //Boolean to check whether it's turned on or off
private var drainSpeed : float = 2.0; //The speed that the energy is drained
function Update () {
if (Input.GetKeyDown(KeyCode.F)) ToggleFlashlight();
}
//When the player press F we toggle the flashlight on and off
function ToggleFlashlight () {
turnedOn=!turnedOn;
if (turnedOn && energy>0) {
TurnOnAndDrainEnergy();
} else {
lightSource.enabled = false;
}
}
//When the flashlight is turned on we enter a while loop which drains the energy
function TurnOnAndDrainEnergy () {
lightSource.enabled = true;
while (turnedOn && energy>0) {
energy -= drainSpeed*Time.deltaTime;
yield;
}
lightSource.enabled = false;
}
//This is called from outside the script to alter the amount of energy
static function AlterEnergy (amount : int) {
energy = Mathf.Clamp(energy+amount, 0, 100);
}
Answer by swatmaster69 · Nov 09, 2012 at 10:47 PM
Something like this should work if all you want is the text:
function OnGUI () {
GUI.Label (Rect (10, 10, 150, 20), Flashlight.energy.ToString());
}
If you want more of a power bar, this is how it's done in Game Development with Unity by Michelle Menard:
function OnGUI () {
GUI.BeginGroup( Rect(40, 10, 218 * (health/10.0) +35 , 90) );
GUI.Label( Rect(0, 0, 272, 90), hBarImage );
GUI.EndGroup();
}
For you, health would be Flashlight.energy and 10.0 would be 100. hBarImage is an image of an energy bar. The idea is that everything in the group is clipped to the size of the BeginGroup rectangle, so when that rectangle shrinks with the health, the power bar appears to shrink too.
I put in the second coding you gave me and replaced heal and 10.0 but it gives me an error "expecting (, found '{'. I made it in Javascript, cleared the coding then placed in the coding u gave me.
I forgot the parentheses on the second code snippet. See how the OnGUI function takes no parameters? It still needs the parentheses. I edited the answer, so it should work now.
It's fine, got it work before you replied but had another error. turned out it needed an image for the hBarImage. $$anonymous$$ade the variable on the top, var hBarImage = Texture;
Yeah, you have to provide your own horizontal bar image of course.
Your answer
![](https://koobas.hobune.stream/wayback/20220613083617im_/https://answers.unity.com/themes/thub/images/avi.jpg)