Hi, I am making a health bar for my game, but when I play, everytime I collide with the wall that has the tag Daño, the game stops and there are two messanges. That first says NullReferenceException: Object reference not set to an instance of an object Health.Start () (at Assets/Scripts/Health.cs:16) and the second says NullReferenceException: Object reference not set to an instance of an object Health.TakeDamage (System.Int32 damage) (at Assets/Scripts/Health.cs:36) Health.OnCollisionEnter (UnityEngine.Collision other) (at Assets/Scripts/Health.cs:29). Can someone please help me? Here is my code.
Script HealthBar:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HealthBar : MonoBehaviour
{
public Slider slider;
public void SetMaxHealth(int health)
{
slider.maxValue = health;
slider.value = health;
}
public void SetHealth(int health)
{
slider.value = health;
}
}
Script Health:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Health : MonoBehaviour
{
public int maxHealth = 100;
public int currentHealth;
public HealthBar healthBar;
// Start is called before the first frame update
void Start()
{
currentHealth = maxHealth;
healthBar.SetMaxHealth(maxHealth);
}
// Update is called once per frame
void Update()
{
}
private void OnCollisionEnter(Collision other)
{
if(other.collider.tag == "Daño")
{
TakeDamage(20);
}
}
void TakeDamage(int damage)
{
currentHealth -= damage;
healthBar.SetHealth(currentHealth);
}
}