- Home /
How to assign callback function to Slider.onValueChanged
Hi all, in the following script I'm trying to assign a callback function to 4.6 UnityEngine.UI.Slider.onValueChanged to do something in this OverSlider class which attached to a UnityEngine.UI.Slider. The documentation doesn't give a hint and I didn't find any examples. Could you please tell me how to change the two commented lines?
Thank you.
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class OverSlider : MonoBehaviour {
Slider slider;
float value = 0f;
void Awake () {
slider = gameObject.GetComponent<Slider> ();
slider.onValueChanged = A(); ///////// HOW DO I ASSIGN HERE?
}
void Update () {
value = slider.value;
}
void A(Slider.SliderEvent se) ///////// HOW DO I DECLARE THIS?
{
// ...
}
}
And the fired error is:
Assets/Scripts/OverSlider.cs(14,41): error CS1501:
No overload for method 'A' takes '0' arguments
And if I get rid of parentheses:
Assets/Scripts/OverSlider.cs(14,24): error CS0428:
Cannot convert method group 'A' to non-delegate type 'UnityEngine.UI.Slider.SliderEvent'.
Consider using parentheses to invoke the method
Comment
Best Answer
Answer by CodeElemental · Jan 27, 2015 at 03:51 PM
Try
slider.onValueChanged.AddListener(ListenerMethod);
public void ListenerMethod(float value)
{
}
Answer by Rs · Aug 24, 2015 at 02:24 PM
Define a function that responds to the valueChanged event
void valueUpdate()
{
float sliderValue = mySlider.value;
// ...
}
...and set it as a delegate in your Start function
void Start() {
mySlider.onValueChanged.AddListener(
delegate { valueUpdate();}
);
}