Introduction
In this article, you will learn how to create a UI slider with text that shows percentage value using C# Script in Unity 3D.
Prerequisites
- Unity Environment version 2018.4.25f1
Create the project
Create the UI Text (user interface) in unity
First, create new UI Text if there is no canvas. It is created automatically. Then, click on the "GameObject" menu in the menu bar.
Select UI and pick the "Text" option.
Position it in the right middle holding out + Shift keys change its text field modify its font size set overflow change.
Right-click on the canvas and create a new UI slider.
Select UI and pick the "Slider" option.
Select UI slider scale model in the scene view.
Create a C# Script
Right-click on Assets.
Select Create >> C# script.
Rename the script as percentage show value.
Double click on the MoveScript script. The MonoDevelop-Unity editor will open up.
Copy and paste the below code,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PercentageShowValue: MonoBehaviour {
Text percentageText;
void Start() {
percentageText = GetComponent < Text > ();
}
public void textUpdate(float value) {
percentageText.text = Mathf.RoundToInt(value * 100) + "%";
}
}
Save the program.
Drag and drop the Percentage ShowValue onto the Text.
Now the last thing we need to do is simply hook up our Slider to the function that we just created.
To do that let's select the button and scroll down where it says on click "this is unity".
We can add an action to this event by hitting the plus button.
We need to select an object that will be our text.
Let's drag that in there, now we can go and find our PercentageShowValue script here we will create a function call textUpdate.
Let's hit play and see how it works.
Summary
I hope you understood how to create a UI slider with text that shows percentage value using C# Script in Unity 3D.