Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

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

Discussion in 'UGUI & TextMesh Pro' started by jerotas, Dec 3, 2014.

  1. jerotas

    jerotas

    Joined:
    Sep 4, 2011
    Posts:
    5,555
    Hi, I've got onValueChanged code for a Slider working like this:

    Code (csharp):
    1.  
    2. void OnEnable() {
    3.    slider.onValueChanged.AddListener(SliderChanged);
    4. }
    5.  
    6. private void SliderChanged(float newValue) {
    7.   // do something
    8. }
    9.  
    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 :(
     
    Last edited: Dec 3, 2014
  2. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    556
    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):

    Code (csharp):
    1. using UnityEngine.EventSystems;
    2.  
    3. Slider slider = ...;
    4. EventTrigger.Entry triggerEntry = newEventTrigger.Entry();
    5. triggerEntry.eventID = EventTriggerType.Drag;
    6. triggerEntry.callback.AddListener(delegate{SliderDragged();});
    7. slider.GetComponent<EventTrigger>().delegates.Add(triggerEntry);
    8.  
    9. void SliderDragged(){
    10.     Debug.Log("I'm not sure if this is every frame while dragging, or just when starting to.");
    11. }
    The fact that methods are virtual simply means that you can override them in any subclasses you may create. =)
     
  3. jerotas

    jerotas

    Joined:
    Sep 4, 2011
    Posts:
    5,555
    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 :)
     
  4. Senshi

    Senshi

    Joined:
    Oct 3, 2010
    Posts:
    556
    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!
     
  5. jerotas

    jerotas

    Joined:
    Sep 4, 2011
    Posts:
    5,555
    Cool thanks!