0

I was trying to apply damage to my health bar like the code below then I tried combining it with my other code but getting this error:

NullReferenceException: Object reference not set to an instance of an objectDistroy.damagebybullet ()

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class healthbar : MonoBehaviour
{
    public float darah;
    public float maxHealth;

    public GameObject healthBarUi;
    public Slider slider;
    private void Start()
    {
        darah = maxHealth;
        slider.value = CalculateHealth();
    }
    public void update()
    {
        slider.value = CalculateHealth();
        if (darah < maxHealth)
        {
            healthBarUi.SetActive(true);
        }
        if (darah <= 0)
        {
            Destroy(gameObject);
        }
        if (darah > maxHealth)
        {
            darah = maxHealth;
        }
    }
    float CalculateHealth()
    {
        return darah / maxHealth;
    }
}

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Distroy : MonoBehaviour
{
   [SerializeField] public float damangebullet;
    private healthbar hai;
    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.collider.CompareTag("Enemy"))
        {
            damagebybullet();
        }

    }
    void damagebybullet()
    {
        hai.darah -= damangebullet;
        hai.update();
    }
}
Milo
  • 3,002
  • 9
  • 25
  • 40
  • Welcome to Stack Overflow. Presumably `hai` is null. It's not obvious to me what you expect to be populating that field. See https://stackoverflow.com/questions/4660142 for more details. – Jon Skeet Mar 06 '20 at 13:51
  • You never assign `hai` – derHugo Mar 06 '20 at 13:51

0 Answers0