Object reference not set to an instance of an object error in my script

Being told “NullReferenceException; Object reference not set to an instance of an object” on line 24?
Really new so don’t be harsh if its obvious but any clue what i’ve done wrong?

using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using UnityEngine;

public class PlayerCombat : MonoBehaviour
{
    public int maxHealth = 5;
    public int currentHealth;
    public HealthBar healthBar;

    public Animator animator;

    public Transform AttackPoint;
    public LayerMask enemyLayers;

    public float attackRange = 0.5f;
    public int attackDamage = 2;


    void Start()
    {
        currentHealth = maxHealth;
        healthBar.SetMaxHealth(maxHealth);
    }

    // Update is called once per frame
    void Update()
    {
     
        if (Input.GetMouseButtonDown(0))
        {
            Attack();
        }
    }

    void Attack()
    {
        // play animation
        animator.SetTrigger("Attack");

        // Detect enemies in range of attack
        Collider2D[] hitEnemies = Physics2D.OverlapCircleAll(AttackPoint.position, attackRange, enemyLayers);

        // Damage
        foreach(Collider2D enemy in hitEnemies)
        {
            enemy.GetComponent<Enemy>().TakeDamage(attackDamage);
        }
    }

    void OnDrawGizmosSelected()
    {
        if (AttackPoint == null)
            return;

        Gizmos.DrawWireSphere(AttackPoint.position, attackRange); 
    }

    void hit()
    {

    }

    void TakeDamage(int damage)
    {
        currentHealth -= damage;

        healthBar.SetHealth(currentHealth);

        if (currentHealth <= 0)
        {
            Die();
        }

    }

    void Die()
    {
        UnityEngine.Debug.Log("You Died");

        // die animation

        // disable self
    }

}

Line 25 on this post coz it uploaded weird. Something about my healthBar

If HealthBar class is a MonoBehaviour, first select the object with the PlayerCombat component in your scene, then look in the Inspector to make that you have something assigned to “Health Bar” (and drag your health bar to it, if things are set up that way) - otherwise you’ll have to look wherever it’s being assigned procedurally, i.e. search for .healthBar =

1 Like