Search Unity

  1. Unity 2019.2 is now released.
    Dismiss Notice

Player Health Bar UI Is Returning "Object reference not set to an instance of an object"

Discussion in 'Scripting' started by unity_8g7XwYU6kpaB-Q, Aug 23, 2019.

  1. unity_8g7XwYU6kpaB-Q

    unity_8g7XwYU6kpaB-Q

    Joined:
    Aug 17, 2019
    Posts:
    9
    My PlayerUI script is as follows:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerUI : MonoBehaviour
    6. {
    7.    
    8.     [SerializeField]
    9.     RectTransform healthBarFill;
    10.    
    11.     private PlayerUnit player;
    12.    
    13.    
    14.     public void SetPlayer (PlayerUnit _player)
    15.     {
    16.         player = _player;
    17.  
    18.     }
    19.     // Start is called before the first frame update
    20.     void Start()
    21.     {
    22.         SetHealthAmount(player.GetHealth());
    23.     }
    24.  
    25.     // Update is called once per frame
    26.     void Update()
    27.     {
    28.        
    29.     }
    30.    
    31.     void SetHealthAmount(float amount)
    32.     {
    33.         healthBarFill.localScale = new Vector3(1f, amount, 1f);
    34.     }
    35. }
    36.  
    Please lead me in the right direction, I feel like I almost have all of this down, this is just a passion project, no harsh words please.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    6,669
    That means something is null, and you're trying to "dig into" that null thing; but because it's null, that's impossible. If the error points you to line 22, then player is null (which presumably means "SetPlayer" was never called). If it points you to line 33, it means you forgot to assign healthBarFill.
     
    Joe-Censored likes this.
  3. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    6,511
    This ^^^

    Also, using the "player" reference in Start is probably a bad idea, unless when this object is created this script is disabled. If the script is enabled from the beginning, then you're not giving yourself much opportunity to call SetPlayer before the Start method is automatically called.

    I'd probably just move the call to SetPlayerHealth to the end of the SetPlayer method. That way SetPlayerHealth is called as soon as the player reference gets set, but not attempted before.