Can't use UnityEngine.UI

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Health : MonoBehaviour
{

    Slider slider;

    // Start is called before the first frame update
    void Start()
    {
       slider.value = 1;
    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log(slider.value);
    }
}

When I run the code this error is shown :

NullReferenceException: Object reference not set to an instance of an object
Health.Update () (at Assets/Test/Health.cs:20)

Slider and UI is underlined red.
I can’t seem to understand the problem here.
And UnityEngine.UIElements is shown in the dropdown list whereas UnityEngine.UI is not found.

Please Help.

Your NullReferenceException is because you haven’t assigned “slider” to anything. You need to either make it public and drag a Slider into that slot in Health’s inspector, or you can use GetComponent<> in Start to assign it.

Your red underlines and dropdown list is unrelated, and solely a Visual Studio issue. Try the steps given here to resolve that.

1 Like

Well, That solved the problem.
Thanks mate.

1 Like