Hey all. I’m getting a NullReferenceException when I run the following code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Health : MonoBehaviour {
public float maxHealth, currentHealth;
public Slider healthSlider;
Attackers attackers;
void Start()
{
attackers = GameObject.Find("Lizard").GetComponent<Attackers>();
healthSlider.maxValue = maxHealth;
healthSlider.value = maxHealth;
}
}
I’m dragging the slider in from the inspector and it seems to be there. It accepts the slider I drag in, but it’s not recognising it when I run the game. Any ideas?
By the way, the canvas is in world space. I’m trying to put a slider over the head of an object. Is the issue that I’m dragging in a slider that’s a child of the canvas, rather than an object?
Edit: If I use GameObject.FindObjectOfType() to get the reference it works fine. Dragging it in the inspector just doesn’t work for whatever reason. Would still like to know why, if anyone has any ideas.
Edit: Sorry for all the edits. Just thinking out loud. If I dragged in the canvas, would that have worked since the Slider is a component and not an object?