Problems with GUI.Box


I’m trying to create a healthbar above the enemies in my game.

What I have so far is something like this


Its pretty simple.

However, I am running into problems when I start to decrement the width of the healthbar (to symbolise when the enemies get hurt)

When I get into the low numbers (less than 6 or so), the healthbar actually changes direction for some reason. The following picture is the width at 32 compared with the width at 2.


This is my code:

    void Start ()
        color = new Color(255, 0, 0);

        texture = new Texture2D(1, 1);
        texture.SetPixel(0, 0, color);

        height = 5;
        width = 32;

        health = width;

        decrement = width / 100;

        healthBar = new Rect();
        healthBar.size = new Vector2(width, height);

        healthBar.position = new Vector2(100, 100);

    private void OnGUI()

 = texture;
          GUI.Box(healthBar, GUIContent.none);


You actually modify the built-in “box” style (which is not recommended). A GUIStyle has many settings which includes border, margin and padding. You’re usually better off with creating your own GUIStyle and set it up the way you need it. The easiest WYSIWYG solution is to create a GUI Skin asset which you use in your script. That way you can tweak all parameters even at runtime to see the effect. You may want to have a look at my IMGUI crash course.