Sliders: Object reference not set

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?

Are you sure you’re getting it for the slider and not the ‘attackers’?

It’s no problem to drag a child of the canvas.

What do you mean? Apologies. As you know, I’m still a newbie. :wink:

I’m dragging in the slider from the canvas into where it asks for the slider in the inspector. It accepts the slider, but when I start the game I get the error.

Okay, well I saw your edits now. Are you dragging the slider to a prefab (asset) by any chance, instead of an object in the scene?

No. The object is prefabbed, but I’m dragging it onto an object that’s currently in the scene.

By the way, in case anyone needs an answer to this or makes the same mistake I did. I forgot that I’d put the script on multiple objects, so about 7 of them didn’t have the slider reference.

Ah yes, that can happen. :slight_smile: Glad you got it worked out.