Sliders are used a lot in video games. As a result, we have to display some percentage of the slider to give the player a better visual idea of what he is changing. For example, when the player is tweaking an ability parameter, it could be useful if the amount remaining is displayed as a percentage. The goal of this recipe is to create a script that shows the value of the slider in percentage. As such, we will develop a script that will use both the Slider (Script) and Text (Script) components.
using UnityEngine.UI;
statement at the beginning of the script. Before the class, we can also add the following line: [RequireComponent(typeof(Text))]
(without the semicolon at the end). In this way, we are saying that, in order to use this script, it requires a Text (Script) component attached to the same game object of this script.private Text uiText;
.float
as a parameter (the value of the slider) and changes it to string
that represents that number in a percentage. To do this, we multiply the value by 100 and round it off using the Mathf.RoundToInt()
function. In addition, by doing this, we get to see all percentages with decimals. Finally, add %
at the end of the string. We put this string into the text
variable of the Text (Script)
component. Therefore, we can write the function in the following way:public void updateValue(float value){ uiText.text = Mathf.RoundToInt (value * 100) + "%"; }
The Slider (Script) component has a variable called value
that stores the position of the slider as float
between 0
and 1
. In order to show this number, we passed it through an event — OnValueChange. This happens every time the player changes the value of the slider, that is, every time the slider is dragged. When this event happens, a value is passed to our script. This first transforms the number into an integer between 0 and 100, and then converts it into a formatted string to show it as a percentage. Finally, this string is shown in the Text (Script) component.
3.22.74.232