I’m trying to set up a health bat that goes down whenever the player takes damage. Just for testing purposes, I created an empty game object and used that as a trigger to decrease the health bar when the player walks into it.
Here’s the code attached to the health bar UI
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class HealthBarController : MonoBehaviour {
public Image healthBar;
private float startHealth = 1.0f;
private float currentHealth;
// Use this for initialization
void Start ()
{
currentHealth = startHealth;
GetHealth();
}
void GetHealth ()
{
healthBar.fillAmount = currentHealth;
}
}
and here’s the code on the trigger that I want to use to decrease the player’s health bar when they enter it.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class TestDamageScript : MonoBehaviour
{
HealthBarController HPcontroller;
void Start ()
{
HPcontroller = GetComponent<HealthBarController>();
}
void OnTriggerEnter2D (Collider2D entity)
{
if (entity.tag == "Player")
{
HPcontroller.healthBar.fillAmount -= 0.5f;
}
}
}
whenever I run the scene, everything works as it should until I enter the trigger where it throws back:
NullReferenceException: Object reference not set to an instance of an object
TestDamageScript.OnTriggerEnter2D (UnityEngine.Collider2D entity) (at Assets/Scripts/TestDamageScript.cs:18)
I know the error is probably my logic behind the HPcontroller.healthBar.fillAmount. I’m just not sure what to do to start fixing it.