- Home /
See the battery on GUI
I have this script : using UnityEngine; using System.Collections; [RequireComponent(typeof(Light), typeof(AudioSource))] public class flashlight : MonoBehaviour { public AudioClip clickSound; public float batteryLifeInSec = 300f; public float batteryPercentage = 100; private bool on; private float timer; void Update() { Light lite = GetComponent(); timer += Time.deltaTime; if(Input.GetKeyDown(KeyCode.F) && timer >= 0.3f && batteryPercentage > 0) { on = !on; audio.PlayOneShot(clickSound); timer = 0; } if(on) { lite.enabled = true; batteryPercentage -= Time.deltaTime * (100 / batteryLifeInSec); } else { lite.enabled = false; } batteryPercentage = Mathf.Clamp(batteryPercentage, 0, 100); if(batteryPercentage == 0) { lite.intensity = Mathf.Lerp(lite.intensity, 0, Time.deltaTime * 2); } if(batteryPercentage > 0 && batteryPercentage < 25) { lite.intensity = Mathf.Lerp(lite.intensity, 0.5f, Time.deltaTime); } if(batteryPercentage > 25 && batteryPercentage < 75) { lite.intensity = Mathf.Lerp(lite.intensity, 0.8f, Time.deltaTime); } if(batteryPercentage > 75 && batteryPercentage <= 100) { lite.intensity = Mathf.Lerp(lite.intensity, 1, Time.deltaTime); } } }
I would like to see the variable batteryPercentage on GUI , i tried to call the method OnGUI() but there is an error , and i put the function after the update function what am i doing wrong ?
@TonyLi: I would give you an upvote for each question if possible... :D
At the moment this is just a badly formatted and badly worded "write me some code" - question.
Answer by TonyLi · May 13, 2013 at 07:06 PM
For a text label (e.g., "Battery: 100%") try:
void OnGUI() {
GUI.Label(new Rect(25, 25, 200, 30), string.Format("Battery: {0}%", batteryPercentage));
}
For an energy bar try:
public Texture barBackground; // Assign a texture for the battery bar background
public Texture barForeground; // Assign a texture for the battery bar foreground
void OnGUI() {
GUI.DrawTexture(Rect(25, 25, 100, 30), barBackground);
GUI.DrawTexture(Rect(25, 25, 100 * batteryPercent, 30), barForeground);
}
Warning: untested code. I'm not near Unity at the moment.
Your answer
![](https://koobas.hobune.stream/wayback/20220613102146im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Window Background Image not showing 1 Answer
GuiTexture Width Change 1 Answer
NGUI: Duplicate/Rotate? 0 Answers
How to Convert each 2D Array to GameObject 2 Answers
On hover GUI text change position. 1 Answer