How to script the other Events for a slider? Only onValueChanged seems to be compilable!

Hi, I’ve got onValueChanged code for a Slider working like this:

void OnEnable() {
   slider.onValueChanged.AddListener(SliderChanged);
}

private void SliderChanged(float newValue) {
  // do something
}

But there are a whole bunch of other events on the Slider that start with capital O, like OnBeginDrag. How do I script handlers for those? There’s no AddListener method on any of them. Intellisense says they are public virtual methods, if that matters.

I already Googled, found nothing. Rather worried because about half the threads on this forum are unanswered :frowning:

I’m guessing OnValueChanged is receiving the same special treatment Button’s OnClick is due to it being used a lot (relative to the others). To add other listeners, you can do the following (untested; adapted from my Button code):

using UnityEngine.EventSystems;

Slider slider = ...;
EventTrigger.Entry triggerEntry = newEventTrigger.Entry();
triggerEntry.eventID = EventTriggerType.Drag;
triggerEntry.callback.AddListener(delegate{SliderDragged();});
slider.GetComponent<EventTrigger>().delegates.Add(triggerEntry);

void SliderDragged(){
    Debug.Log("I'm not sure if this is every frame while dragging, or just when starting to.");
}

The fact that methods are virtual simply means that you can override them in any subclasses you may create. =)

Thanks. that assumes that you have an EventTrigger component. I guess I can add one from the Inspector if not.

I’m not likely to create any subclasses, but who knows :slight_smile:

Yes, it does, but I believe that’s a requirement anyway. =) The purpose of overriding the the virtual methods is for when you need specific behaviour to happen. I.e.: If you want to (re)set a certain state on drag/ drop/ anything. Good luck!

Cool thanks!