Health bar performance problem

Hello!
I’ve been recently working on a 2D diablo-like game. Each enemy has a health bar above their head. All good and stuff… except my Health bar OnGUI script is killing my i5 CPU once about 15 enemies are spawned. The game becomes unplayable (~15-20fps).

To set up the health bar above enemies, each enemy has the following script attached:

public class HealthGUI : MonoBehaviour {

    public float percentage; //percentage of health
    public Texture2D healthbarBorder; //GUI health bar border
    public Texture2D healthbar; //GUI health bar

    void Update () {
        percentage = (float)GetComponent<Entity> ().health / (float)GetComponent<Entity> ().maxHealth;
    }

    void OnGUI()
    {
        GUI.DrawTexture (new Rect (Camera.main.WorldToScreenPoint(transform.position).x - 60 ,Screen.height - Camera.main.WorldToScreenPoint(transform.position).y -80,100,20), healthbarBorder);
        GUI.DrawTexture (new Rect (Camera.main.WorldToScreenPoint(transform.position).x -60 ,Screen.height - Camera.main.WorldToScreenPoint(transform.position).y -80,100*percentage,20), healthbar);
    }
}

I have disabled this script and my game worked flawlessly. Turns out it consumes @90% of my CPU. I don’t understand why it’s such a performance issue… I figure there’s a workaround, like drawing the healthbar once and then positioning it to follow the object. Any tips?
Thank you!

tiny tweak. might see just a little improvement.

public class HealthGUI : MonoBehaviour
{
    public float percentage; //percentage of health
    public Texture2D healthbarBorder; //GUI health bar border
    public Texture2D healthbar; //GUI health bar
   
    private Entity _entity = null;
    private Transform _tran = null;

    void Start()
    {
        _entity = GetComponent< Entity >();
        _tran = transform;
    }

    void Update()
    {
        percentage = (float)_entity.health / (float)_entity.maxHealth;
    }

    void OnGUI()
    {
        GUI.DrawTexture( new Rect( Camera.main.WorldToScreenPoint(_tran.position).x - 60, Screen.height - Camera.main.WorldToScreenPoint(_tran.position).y - 80, 100, 20), healthbarBorder );
        GUI.DrawTexture( new Rect( Camera.main.WorldToScreenPoint(_tran.position).x - 60, Screen.height - Camera.main.WorldToScreenPoint(_tran.position).y - 80, 100 * percentage, 20), healthbar );
    }
}
1 Like