This is a multi part question. Sorry if this has been asked before, I’ve searched for awhile and didn’t find what I was looking for.
I’m making a simple meter to represent a battery for a flashlight using two GUI textures(one is just the outline of a battery, the other a gradient of red to green, if it helps).
Here’s my code:
using UnityEngine;
using System.Collections;
public class HUD : MonoBehaviour {
// various textures to display on screen
public Texture2D reticle;
public Texture2D batteryIcon;
public Texture2D batteryMeter;
public float maxBatteryHealth = 100; // the max amount of battery health
public float curBattHealth; // the current amount of battery health
public float batteryDecayRate = 1; // the rate at which the battery will decay
public bool battAreDead = false;
// Use this for initialization
void Start () {
curBattHealth = maxBatteryHealth; // set the current battery health to the max battery health to start
Screen.showCursor = false; // Hide the mouse
}
void OnGUI()
{
// code for the on screen reticle
float xMin = (Screen.width / 2) - (reticle.width / 2); // reticle x position
float yMin = (Screen.height / 2) - (reticle.height / 2); // reticle y position
GUI.DrawTexture (new Rect (xMin, yMin, reticle.width, reticle.height), reticle); // draw the reticle to positions
// Code for the battery icon
GUI.DrawTexture (new Rect (1300, 545, batteryIcon.width / 5, batteryIcon.height / 5), batteryIcon);
// Code for the battery meter
GUI.DrawTexture (new Rect (1300, 545, batteryMeter.width / 5, batteryMeter.height / 5), batteryMeter);
}
// Update is called once per frame
void Update ()
{
if (GameObject.Find("flashlight.GetComponent<Flashlight>().flashLightEnabled") == true) // find the flashlight to
// check if it's on
{
curBattHealth -= Time.deltaTime - (batteryDecayRate * 2); // drain curbattHealth here, the equation is wrong!
}
else
{
// if the flashlight is off, do nothing to the battery
}
if (curBattHealth <= 0)
{
curBattHealth = 0;
battAreDead = true; // if the batteries have no health left they are dead, TO DO: disable the flashlight
}
}
}
Now for the questions:
- How do I fade the battery meter GUI texture based on the value of curBattHealth?
- What’s the code for draining the battery over time? The code I have doesn’t seem to do anything.
- If the flashlight is off, do I need to add code to stop the battery from draining?
- If the flashlight is off, how do I store the curBattHealth?
Pretty new to programming myself so any advice/tips etc. would be greatly appreciated.