Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity send value to UI Slider and update Slider bar

I am pretty new to Unity and was wondering if you could answer this question. I know how i can get the value from the slider both via the script and through a function set in On Value Changed. However is it possible to send back a value to the slider and update the slider bar position in Unity?

like image 350
Silent Ace Avatar asked Jan 14 '16 14:01

Silent Ace


People also ask

How do I set a slider value in unity?

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.

How do you add text to slider in unity?

Create the UI Text (user interface) in unitySelect 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.

How do sliders work in unity?

The slider component is a Selectable that controls a fill, a handle, or both. The fill, when used, spans from the minimum value to the current value while the handle, when used, follow the current value. The anchors of the fill and handle RectTransforms are driven by the Slider.


2 Answers

Are you using the new Unity UI?

Using UnityEngine.UI;

Then you can use a public field to access the Slider

public Slider mSlider;

using Gameobject.Find is very slow so it is best to avoid that whenever possible. You can then assign your slider gameobject to this variable in the Editor.

Then in your Start or Update you can assign the value of the slider like this:

mSlider.value = 0.5f;

and the maximum value of your slider like this:

mSlider.maxValue = 1.0f;

Since the slider value is being set to half of the max value, your slider should be in the middle

like image 131
Govardhan Gosavi Avatar answered Nov 09 '22 01:11

Govardhan Gosavi


If you can get the slider using GameObject.Find, you can set its normalizedValue property to update its position.

Note that GameObject.Find doesn't work on objects that aren't active in the scene, so you may have to grab it when the game starts and assign it to a variable which you can refer to later.

like image 42
John Clifford Avatar answered Nov 09 '22 01:11

John Clifford