I’m working on a variant of the Space Shooter game from Unity’s tutorial. I have created a power-up object that instantiates a shield for your ship when touched, and I’m trying to implement a bar that indicates how long the shield will last. The bar itself is working fine, but I can’t get the bar to start depleting the moment that the shield is instantiated.
My code for the GUI and shield looks like this:
private bool pup = false;
public float barProgress;
public Vector2 pos = new Vector2(10, 50);
public Vector2 size = new Vector2(20, 250);
public Texture2D emptyTex;
public Texture2D fullTex;
void OnGUI()
{
if (pup)
{
GUI.BeginGroup(new Rect(pos.x, pos.y, size.x, size.y));
GUI.Box(new Rect(0, 0, size.x, size.y), fullTex);
GUI.BeginGroup(new Rect(0, 0, size.x, size.y * barProgress));
GUI.Box(new Rect(0, 0, size.x, size.y), emptyTex);
GUI.EndGroup();
GUI.EndGroup();
}
}
void OnTriggerEnter(Collider other)
{
if (other.tag == "pup")
{
GameObject go = Instantiate(shield, shieldSpawn.position, shieldSpawn.rotation) as GameObject;
go.transform.parent = GameObject.Find("Power Ups").transform;
audio_shieldUp.Play();
audio_shieldDown.PlayDelayed(shieldDuration);
Destroy(GameObject.FindWithTag("Shield"), shieldDuration);
Destroy(other.gameObject);
pup = true;
}
}
void Update()
{
if (pup)
{
barProgress = Time.time / shieldDuration;
}
}
The shield instantiates and the bar shows up on screen, but the “barProgress” counter has already started counting and depletes too soon. What am I doing wrong here?
Also, any suggestions for how to remove the bar after shieldDuration has ended, as it’s drawn in the script and not instantiated?