Reader small image

You're reading from  Unity Cookbook - Fifth Edition

Product typeBook
Published inNov 2023
Reading LevelIntermediate
PublisherPackt
ISBN-139781805123026
Edition5th Edition
Languages
Tools
Right arrow
Authors (3):
Shaun Ferns
Shaun Ferns
author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

Sinéad Murphy
Sinéad Murphy
author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy

View More author details
Right arrow

Displaying the value of an interactive UI Slider

A UI Slider is a graphical tool that allows a user to set the numerical value of an object.

A picture containing icon

Description automatically generated

Figure 2.15: Example of a UI Slider offering a range of 0 to 20

This recipe illustrates how to create an interactive UI Slider and execute a C# method each time the user changes the UI Slider value.

How to do it...

To create a UI Slider and display its value on the screen, follow these steps:

  1. Create a new Unity 2D project and install TextMeshPro by choosing: Window | TextMeshPro | Import TMP Essential Resources.
  2. Add a UI Text-TextMeshPro 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 Overflow to Overflow. Since we may change the font and message at a later date, it’s useful to allow overflow to prevent some of the message being truncated.
  3. In the Hierarchy window, add a UI Slider GameObject to the scene by going to GameObject | UI | Slider.
  4. In the Inspector window, modify the settings for the position of the UI Slider GameObject’s Rect Transform to the top-middle part of the screen.
  5. In the Inspector window, modify the settings of Position for the UI Text’s Rect Transform so that they’re just below the slider (top, middle, then Pos Y = -30).
  6. In the Inspector window, set the UI Slider’s Min Value to 0 and Max Value to 20. Then, check the Whole Numbers checkbox:

Figure 2.16: Setting the UI Slider’s Min Value and Max Value

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

Description automatically generated

Figure 2.17: Dragging Slider into the Slider UI variable

  1. Ensure that the Slider GameObject is selected in the Hierarchy window. Then, in the Inspector window, add an OnValue Changed (Single) event handler by clicking on the plus (+) sign at the bottom of the Slider component.
  2. Drag the Text(TMP) GameObject from the Hierarchy window over to the Object slot (immediately below the menu that says Runtime Only), as shown in the following screenshot:
    A screenshot of a computer

Description automatically generated

    Figure 2.18: Dragging the Text GameObject into None (Object)

    You have now told Unity which object a message should be sent to each time the slider is changed.

  1. 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(TMP) GameObject, will be executed:

Figure 2.19: Drop-down menu for On Value Changed

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

How it works...

In this recipe, you created a UI Slider GameObject and set it to contain whole numbers in the range of 0 to 20.

You also added an instance of the SliderValueToText C# script class to the UI Text(TMP) GameObject.

The Awake() method caches references to the Text component in the textSliderValue variable.

The Start() method invokes the ShowSliderValue() method so that the display is correct when the scene begins (that is, the initial slider value is displayed).

The ShowSliderValue() method gets the value of the slider and then updates the text that’s displayed to be a message in the form of Slider value = <n>.

Finally, you added the ShowSliderValue() method of the SliderValueToText scripted component to the Slider GameObject’s list of On Value Changed event listeners. So, each time the slider value changes, it sends a message to call the ShowSliderValue() method so that the new value is updated on the screen.

Previous PageNext Page
You have been reading a chapter from
Unity Cookbook - Fifth Edition
Published in: Nov 2023Publisher: PacktISBN-13: 9781805123026
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €14.99/month. Cancel anytime

Authors (3)

author image
Shaun Ferns

Shaun is a lecturer at Technological University Dublin. He is currently teaching on the BA (Hons) in Creative Digital Media where he is lead in the delivery of the Multimedia Stream. He is currently exploring serious games for construction-related training as well as the opportunities transmedia provides in improving user experience and engagement in cultural archive artifacts. His educational research is currently driven by his interest in self-determined learning (heutagogy), rhizomatic learning theory, micro-credentialing /digital badging, and curriculum development.
Read more about Shaun Ferns

author image
Sinéad Murphy

Sinead Murphy is currently Data Analytics Manager for the Irish NGO Trocaire. She has over 25 years of computing experience, including freelance IT training and database consulting, university lecturing in mathematics, IT skills and programming at TU Dublin (Ireland) and Middlesex University (London). She is a published academic, with undergraduate and postgraduate degrees in mathematics, computing and data science. She is passionate about the use of IT for understanding and visualising data, and using that understanding to make meaningful differences in the world. She is currently exploring the use of Python and Unity for data analytics and interactive visualisations.
Read more about Sinéad Murphy