Search Unity

Optimizing UI bars

Discussion in 'Scripting' started by Josiah_Ironclad, Apr 24, 2020.

  1. Josiah_Ironclad

    Josiah_Ironclad

    Joined:
    Sep 24, 2019
    Posts:
    156
    Every single time I ever made health/mana/xp bars, I always link them in a script, and set their values to local ints and floats, which I change at runtime and such. My question is, do I need to do this at all?

    Code (CSharp):
    1. Slider healthBar;
    2. public int maxPlayerHealth;
    3. public int playerHealth;
    4.  
    5. void Awake() {
    6.  
    7.     healthBar = GameObject.Find("Health Bar").GetComponent<Slider>();
    8. }
    9.  
    10. void Update() {
    11.  
    12.     healthBar.maxValue = maxPlayerHealth;
    13.     healthBar.value = playerHealth;
    14. }
    Is it completely pointless to do it. Could I just reference the slider, and directly change its max and current values when taking damage or gaining XP points?
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,726
    I would not store game "business data" (such as health or whatever) in a slider. You certainly CAN do it, but it isn't a great idea, and here's why: if you store your health in some random piece of UI, what happens if you decide to completely change how health is displayed? That's why generally health is tracked in some code variable, then a script is used purely to display it.

    In your case above you have combined storage and display, but I prefer to separate them: one script would contain everything related to the player's current state (such as health, score, etc.) and when I make a UI, that UI would have specific scripts to display the information.

    If later I redo the UI to (for instance) show the information also on a diagetic item in the physical game screen (such as the spinal cord health bar that Dead Space uses), the underlying business logic does not change, just the display logic.
     
    Josiah_Ironclad and StarManta like this.