Unity - The Slider



In this chapter, we will learn about the last UI element in this series. The Slider is commonly used where a certain value should be set between a maximum and minimum value pair. One of the most common usage of this is for audio volume, or screen brightness.

To create a slider, go to Create → UI → Slider. A new Slider element should show up on your scene.

Slider Element

If you go to the properties of this Slider, you will notice a ist of options to customize it.

Slider properties

Let us try to make a volume slider out of this slider. For this, open the ButtonBehaviour script (you can rename the ButtonManager GameObject as it is certainly doing more than just managing a button now) and add a reference to the Slider. We will also change the code around a bit again.

public class ButtonBehaviour : MonoBehaviour {
   int n;
   public Text myText;
   public Slider mySlider;
   void Update() {
      myText.text = "Current Volume: " + mySlider.value;
   }
}

Understand how we are using the Update method to constantly update the value of myText.text.

In the slider properties, let us check the “Whole Numbers” box, and set the maximum value to 100.

We will set the color of the text through its properties for a more visible color.

Let us follow the same procedure of dragging the Slider GameObject onto the new slot, and hit play.

Dragging the Slider GameObject

It is highly recommended you explore and experiment with the other UI controls as well, to see which ones work in which way.

In our subsequent section, we will learn about lighting, materials and shaders.

Advertisements