- Home /
How to add a function from another class to a Slider's OnValueChanged with AddListener()?
Hello, I'm new to Unity/C# and need quite a bit of help. In my program, I have one UI slider at start and a bunch of prefabs instantiated during runtime. Each prefab has a script that changes its localScale. I want the user to click on a prefab, and the slider's OnValueChanged list of functions to update so it only changes the dynamic variable of the prefab the user clicked on. The only problem is that the last line of StartScaleMode(), where I use AddListener(), does not seem to work.
The function for adding a function to OnValueChanged :
public void StartScaleMode()
{
GameObject ScaleSlider = GameObject.Find("ScaleSlider");
Slider SlideScript = ScaleSlider.GetComponent<Slider>();
Scale script = hit.collider.gameObject.AddComponent<Scale> ();
SlideScript.onValueChanged.AddListener(delegate
{
script.AdjustSize(SlideScript.value);
});
}
And the other class, which is attached to the prefabs, is:
public class Scale : MonoBehaviour {
public void AdjustSize(float newSize)
{
gameObject.transform.localScale += new Vector3(newSize, newSize, newSize);
}
Answer by Hellium · Aug 26, 2019 at 05:28 AM
onValueChanged
is an event taking a float as parameter, so I believe you can do:
SlideScript.onValueChanged.AddListener(script.AdjustSize);
Also, I advise you to remove the event listeners beforehand, if you don't do it already.
SlideScript.onValueChanged.RemoveAllListeners();
Thanks for the help. Unfortunately, when I go to the inspector during runtime, no functions seem to have been added to OnValueChanged event.
This is the expected behaviour, callbacks added at runtime won't appear in the inspector.
Ah I see. When I change the value of the slider, though, the size of the object does not change. I've checked the Physics.Raycast and it returns the correct collider. Any possible ideas as to why or how to find the issue? You have helped me so much already, so don't feel pressured if you have no idea.
Your answer

Follow this Question
Related Questions
Using Listeners for Sequences and Different Classes 1 Answer
Button Listener Takes Reference But I Want to Pass Value? 1 Answer
UI toggle.onValueChanged assigning method via script 1 Answer
Split Screen Game Audio Listeners 5 Answers
Unity 4.6 - Editor Scripting - Add Reflection Method as a Persistent Listener 1 Answer