Search code examples
c#unity-game-enginesliderunity-ui

How do I get a Value from a Slider in Unity?


Everything goes wrong when I try to set a text from a Slider's Value. I used GetComponent<>() for GameObject as Slider, Slider as Slider, but Unity does not like it. I use the needed library from Unity to deal with this, but Unity says the Slider type is invalid (Could not be found). Here's the code (One of the variations, I have too many of them to show all):

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

public class ValueUpdater : MonoBehaviour
{
    public Slider SliderThing;
    public GameObject Text;

    void Start()
    {

    }

    void Update()
    {
        Text.GetComponent<TextMeshPro>().text = SliderThing.Value;
    }
}

Solution

  •     void Update()
        {
            Text.GetComponent<TextMeshPro>().text = SliderThing.value;
        }
    

    Properties are always in lowercase, use .value instead of .Value to get a slider value. https://docs.unity3d.com/2018.2/Documentation/ScriptReference/UI.Slider.html

    I used GetComponent<>() for GameObject as Slider, Slider as Slider, but Unity does not like it. [...] Unity says the Slider type is invalid (Could not be found)

    This is a NullReferenceException, and it means that you're trying to access a reference variable that isn't referencing any object. If GetComponent is returning null, then that means that the game object your script is running on does not have a Slider component.