I currently have this script attached but I’m not even sure where to start.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class SliderUITextUpdate : MonoBehaviour {
string sliderTextString = "0";
Text sliderText;
public void textUpdate (float textUpdateNumber){
textUpdateNumber.ToString (sliderTextString);
sliderText.text = sliderTextString;
}
// Update is called once per frame
void Update () {
}
}
Hi, i made this little script, just add it to your slider (or wherever) and assign a Slider and a Text in the inspector. You can set a unit and the number of decimals to display as well.
It uses the built in Event system.
This also works inside the editor:
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
[ExecuteInEditMode]
public class SliderWithValue : MonoBehaviour {
public Slider slider;
public Text text;
public string unit;
public byte decimals = 2;
void OnEnable ()
{
slider.onValueChanged.AddListener(ChangeValue);
ChangeValue(slider.value);
}
void OnDisable()
{
slider.onValueChanged.RemoveAllListeners();
}
void ChangeValue(float value)
{
text.text = value.ToString("n"+decimals) + " " + unit;
}
}
You will need to place this script on a gameobject, could be the camera.
using UnityEngine;
using UnityEngine.UI;
public class SliderTest : MonoBehaviour
{
string sliderTextString = "0";
public Text sliderText; // public is needed to ensure it's available to be assigned in the inspector.
public void textUpdate (float textUpdateNumber)
{
sliderTextString = textUpdateNumber.ToString();
sliderText.text = sliderTextString;
}
}
I put this on the camera.
I associated the Text component with the Slider Text in the inspector:
On the slider component i associated the Main Camera(could be whatever GameObject you want) to the “On Value Changed” object. I then hit the drop down to select the function/method to associate with the On Value Changed event.
Add your SliderUITextUpdate script to the Text element you want to be updated. Remove the sliderText variable, and make line 11 just this.GetComponent().text = sliderTextString;
(Note: There are slightly better ways of doing this)
In the Inspector for the Slider, at the very bottom, there should be a small light gray area that has the “On Value Changed (Single)” title. Click the little ‘+’ button, and it should create a new line with a dropdown, a draggable zone, a disabled dropdown, and a disabled text box.
Leave the dropdown on “All”, and click the little circle button. Select your Text element from the list. The dropdown next to it should now be populated. Select SliderUITextUpdate > textUpdate.
They should now be attached, and dragging the slider around should update the text.