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();
}
}