NullReferanceError

Hello, I’m new to Unity and I keep getting NullReferanceError when I try to make a HealthBar. I followed multiple tutorials and I keep getting this error and I don’t know what is returning a 0 value. What can I do to fix it?

using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using UnityEngine.InputSystem;


public class PlayerController : MonoBehaviour
{
    HealthBar healthBar;
    Rigidbody2D rigidbody2d;
    public float timeInvincible = 2.0F;
    bool isInvincible;
    float damageCooldown;
    public int maxHealth=10;
    public int health { get { return currentHealth; }}

     int currentHealth=1;
    public float speed = 1.5f,sprint=1.7f;
    Vector2 move;
    public InputAction MoveAction;
    // Start is called before the first frame update
    void Start()
    {
        //QualitySettings.vSyncCount = 0;
        //Application.targetFrameRate = 30;
        currentHealth = maxHealth;

        MoveAction.Enable();
        rigidbody2d=GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        if (isInvincible)
        {
            damageCooldown -= Time.deltaTime;
            if(damageCooldown <= 0 )
            {
                isInvincible = false;
            }
        }

     
            move = MoveAction.ReadValue<Vector2>();
     

    }
    public void ChangeHealth(int amount)
    {
        if (amount != 0)
        {
            if (amount < 0)
            {
                if (isInvincible)
                {
                    return;
                }
                isInvincible = true;
                damageCooldown = timeInvincible;
            }
            currentHealth = Mathf.Clamp(currentHealth + amount, 0, maxHealth);
            healthBar.SetValue(currentHealth);
            
         
        }
    }
    private void FixedUpdate()
    {
        if (Keyboard.current.shiftKey.isPressed)
        {
            Vector2 position = (Vector2)rigidbody2d.position + move * sprint * Time.deltaTime;
            rigidbody2d.MovePosition(position);
        }
        else
        {
            Vector2 position = (Vector2)rigidbody2d.position + move * speed * Time.deltaTime;
            rigidbody2d.MovePosition(position);
        }
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class healthitem : MonoBehaviour
{
    void OnTriggerEnter2D(Collider2D other)
    {
     
            PlayerController controller = other.GetComponent<PlayerController>();
            if (controller != null && controller.health < controller.maxHealth)
            {

                controller.ChangeHealth(1);
                Destroy(gameObject);
            }
        }
 
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class spikeitem : MonoBehaviour
{
    // Start is called before the first frame update
    void OnTriggerStay2D(Collider2D other)
    {
     
            PlayerController controller = other.GetComponent<PlayerController>();
            if (controller != null)
            {
                controller.ChangeHealth(-1);

            }
     
    }
}
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using TMPro;
using UnityEngine;
using UnityEngine.UI;


public class HealthBar : MonoBehaviour
{
    [SerializeField]
    private PlayerController health;
    [SerializeField]
    private RectMask2D mask;
    [SerializeField]
    private RectTransform barRect;
    [SerializeField]
    private TextMeshProUGUI HealthIndex;
    private float maxRightMask;
    private float initialRightMask;
    // Start is called before the first frame update
    void Start()
    {
        maxRightMask = barRect.rect.width - mask.padding.x - mask.padding.z;
        HealthIndex.SetText(sourceText:$"{ health.health}/{ health.maxHealth}");
    }

     public void SetValue( int newValue)
    {
        var targetWidth= newValue * maxRightMask / health.maxHealth;
        var newRightMask=maxRightMask+initialRightMask - targetWidth;
        var padding= mask.padding;
        padding.z= newRightMask;
        mask.padding = padding;
        HealthIndex.SetText(sourceText: $"{newValue}/{health.maxHealth}");

    }
 
    void Update()
    {
     
    }
}

Your healthBar field in the PlayerController class is indeed never initialized, meaning it’s always null. You need to pass a reference to an instance of HealthBar. One way to do this is by making the healthBar field public. Then, in the Inspector, this field will appear, allowing you to drag and drop the object from the scene hierarchy onto it, which contains the required HealthBar component.
Alternatively, if the PlayerController and HealthBar are on the same object, you can obtain a reference to the required component using the GetComponent() method, similar to how you did it in Start by getting a reference to Rigidbody2D.

Of course, there are other options available.

1 Like

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that
1 Like

Thank you so much, making the field public solved it