Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question A rectangle is visible although its width is 0

Discussion in 'Scripting' started by Krosenut, Jun 9, 2023.

  1. Krosenut

    Krosenut

    Joined:
    Jun 1, 2023
    Posts:
    5
    I'm drawing a rectangle on screen to represent player health. When player's health reaches zero, the rectangle should not be visible, however although debug log confirms that its width is zero, it's still visible on the screen.



    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class UI : MonoBehaviour
    6. {
    7.     Texture2D texture;
    8.     GUIStyle guiStyle;
    9.     bool started;
    10.     public GameObject drone;
    11.     DroneControl droneControl;
    12.    
    13.     void Start()
    14.     {
    15.     }
    16.  
    17.     private void OnGUI()
    18.     {
    19.         if (!started)
    20.         {
    21.             texture= new Texture2D(1,1);
    22.             texture.SetPixel(0, 0, Color.cyan);
    23.             texture.wrapMode = TextureWrapMode.Repeat;
    24.             texture.Apply();
    25.             guiStyle =new GUIStyle(GUI.skin.box);
    26.             guiStyle.normal.background = texture;
    27.             started = true;
    28.             droneControl=drone.GetComponent<DroneControl>();
    29.         }
    30.         float width = droneControl.integrity / 100f * Screen.width / 2;
    31.         if (width <= 0)
    32.             width = 0;
    33.         Rect position = new Rect(Screen.width/2-width/2,Screen.height/4*3 ,width, 10);
    34.         Debug.Log(position);
    35.         GUI.Box(position, GUIContent.none,guiStyle);
    36.     }
    37. }
     
  2. tduriga

    tduriga

    Joined:
    Dec 9, 2015
    Posts:
    52
    If you check all properties in GUIStyle (Unity - Scripting API: GUIStyle (unity3d.com)) you will find that it contains "padding" property that is described as "Space from the edge of GUIStyle to the start of the contents."

    If I look at the padding values for GUI.skin.box style, they are all set to 4 (Left 4, Right 4, Top 4, Bottom 4). Try to change it to zero. (I haven't tested it, so I hope this helps).
     
    Bunny83 likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,561
  4. Krosenut

    Krosenut

    Joined:
    Jun 1, 2023
    Posts:
    5
    Thank you