Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

UI Stamina bar is not working after building

Discussion in 'UGUI & TextMesh Pro' started by supergula, Sep 30, 2019.

  1. supergula

    supergula

    Joined:
    Sep 2, 2017
    Posts:
    1
    Hi everyone,

    I created a game where I have stamina and hence a stamina bar.
    While playing in the editor, the stamina bar works fine and decreases every time I jump.

    After building the game, the bar is shown but isn't adjusting. The stamina is changed though.

    Here is the stamina bar code:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class LifeBar : MonoBehaviour
    7. {
    8.  
    9.     private const float MAX_HEALTH = 100f;
    10.  
    11.     public float currentStamina = MAX_HEALTH;
    12.  
    13.     private Image healthBar;
    14.  
    15.     // Start is called before the first frame update
    16.     void Start()
    17.     {
    18.         healthBar = GetComponent<Image>();
    19.     }
    20.  
    21.     // Update is called once per frame
    22.     void Update()
    23.     {
    24.         currentStamina = GameObject.Find("Dragon").GetComponent<DragonMovement>().stamina;
    25.         healthBar.fillAmount = currentStamina / MAX_HEALTH;
    26.     }
    27. }
    28.  
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    My guess is that your "Find" function is not finding the "Dragon" for some reason, causing your Update code to abort with a Null Reference Exception. Possibly because your build started in a different scene than you did in the editor, or some other difference in early program flow.

    By the way, "Find' is kind of expensive, so calling it every frame in Update is generally a bad idea. It would be a lot more efficient if you found it once (say, in Start) and then saved the DragonMovement component in a variable so that you don't have to go find it again every frame.