Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Can't use UnityEngine.UI

Discussion in 'Scripting' started by alimrafeek, May 19, 2020.

  1. alimrafeek

    alimrafeek

    Joined:
    May 22, 2018
    Posts:
    14
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using UnityEngine.UI;
    5.  
    6. public class Health : MonoBehaviour
    7. {
    8.  
    9.     Slider slider;
    10.  
    11.     // Start is called before the first frame update
    12.     void Start()
    13.     {
    14.        slider.value = 1;
    15.     }
    16.  
    17.     // Update is called once per frame
    18.     void Update()
    19.     {
    20.         Debug.Log(slider.value);
    21.     }
    22. }
    23.  
    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.
     
  2. StarManta

    StarManta

    Joined:
    Oct 23, 2006
    Posts:
    8,741
    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.
     
    Joe-Censored likes this.
  3. alimrafeek

    alimrafeek

    Joined:
    May 22, 2018
    Posts:
    14
    Well, That solved the problem.
    Thanks mate.
     
    Joe-Censored likes this.