
上QQ阅读APP看书,第一时间看更新
How to do it...
To create a UI Slider and display its value on the screen, follow these steps:
- Create a new 2D project.
- Add a UI Text GameObject to the scene with a Font size of 30 and placeholder text, such as slider value here (this text will be replaced with the slider value when the scene starts). Set Horizontal- and Vertical- Overflow to Overflow.
- In the Hierarchy add a UI Slider GameObject to the scene – choose menu: GameObject | UI | Slider.
- In the Inspector, modify the settings for the position of the UI Slider GameObject's Rect Transform to the top-middle part of the screen.
- In the Inspector, modify settings for Position of the UI Text's Rect Transform to just below the slider (top, middle, then Pos Y = -30).
- In the Inspector, set the UI Slider's Min Value to 0, the Max Value to 20, and check the Whole Numbers checkbox:

- Create a C# script class called SliderValueToText, containing the following code, and add an instance as a scripted component to the Text GameObject:
using UnityEngine; using UnityEngine.UI; public class SliderValueToText : MonoBehaviour { public Slider sliderUI; private Text textSliderValue; void Awake() { textSliderValue = GetComponent<Text>(); } void Start() { ShowSliderValue(); } public void ShowSliderValue () { string sliderMessage = "Slider value = " + sliderUI.value; textSliderValue.text = sliderMessage; } }
- Ensure that the Text GameObject is selected in the Hierarchy. Then, in the Inspector, drag the Slider GameObject into the public Slider UI variable slot for the Slider Value To Text (Script) scripted component:

- Ensure that the Slider GameObject is selected in the Hierarchy. Then, in the Inspector, drag the Text GameObject into the public None (Object) slot for the Slider (Script) scripted component, in the section for On Value Changed (Single) - as shown in the screenshot:

Registering an object to receive UI event messages
You have now told Unity to which object a message should be sent each time the slider is changed.
You have now told Unity to which object a message should be sent each time the slider is changed.
- From the drop-down menu, select SliderValueToText and the ShowSliderValue() method, as shown in the following screenshot. This means that each time the slider is updated, the ShowSliderValue() method, in the scripted object, in the Text GameObject will be executed:

- When you run the Scene, you will now see a UI Slider. Below it, you will see a text message in the form Slider value = <n>.
- Each time the UI Slider is moved, the text value shown will be (almost) instantly updated. The values should range from 0 (the leftmost of the slider) to 20 (the rightmost of the slider).