Unity3d health bar GUI element

1k views Asked by At

I want to create a health bar using information that I'm currently displaying in a GUItext. The behaviour I want is for the health to decrease over time (like a countdown timer), but increase by a small amount whenever the player collects an object.

Here is my current code:

using UnityEngine;
using System.Collections;

public class TimeText : MonoBehaviour {

    public GUIText timeText;
    //countdown
    public float timer = 99.00f;

    // Update is called once per frame
    void Update () 
    {
        timer -= Time.deltaTime*5;

        timeText.text = "Health: " + timer.ToString("0");

    }
}

Here is what I would like my health bar to look like: enter image description here

1

There are 1 answers

7
andeart On BEST ANSWER

As @JoeBlow mentioned above, avoid the old GUI mechanics. They are super heavy, crude, and not performance-helpful.

@Serlite broke down the question for you. Those are what you need.

For the health-bar, I suggest using Unity UI's Image component. Use the image you want (possibly the same one you posted in your question?) for the health bar and change the fillAmount based on your timer variable (though personally, I would rename that to something like "health" to represent its purpose better).

It looks like you've already taken care of reducing the health over time. To add to the health, use Colliders as triggers in the scene, and OnTriggerEnter or any of the similar default monobehavior methods on the appropriate objects.

I suggest going through a couple tutorials online, so that you get a better understanding of programming logic in Unity. I hope that helps!