2

how do I add a listener on Unity GUI Slider to listen to the mouse down event on the slider handle?

Thank you in advance!

PastAndSalmon
  • 175
  • 2
  • 11

1 Answers1

10

Unity UI Slider already listens to OnPointerDown as you can see it in the docs.

If you want to change the way it behaves or add some custom behaviour to this method you can do it different ways:

1- Add an EventTrigger to your object and selecting the OnPointerDown event as follow:

EventTrigger component added to a GameObject

2- Declaring a new class that inherits from Slider class and overriding the OnPointerDown() method like this:

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;

public class CustomSlider: Slider
{
    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);

        // Your code here
    }
}

Note the second method will detect pointer down event on all the slider graphics while you can attach the EventTrigger component to the handle alone to detect pointer down event on this graphic element only.

Hope this helps,

Kardux
  • 2,117
  • 1
  • 18
  • 20
  • To anyone who downvoted please explain why: I'd be more than happy to improve my answer subsequently :) – Kardux Jun 23 '17 at 08:11
  • How do I use method #2? I created the script subclassing the Slider, but how do I add this custom slider to a Canvas object like I would do with a regular slider? – SirPaulMuaddib Dec 11 '18 at 02:20
  • @SirPaulMuaddib You simply have to go on your GameObject, click _Add component_ and search for _CustomSlider_ component. Also make sure the .cs file name matches the class name: otherwise Unity won't recognize it as a component. – Kardux Dec 12 '18 at 10:49
  • Actually works perfectly, didn´t know you can also add event trigger as component, awesome. – jsanchezs Oct 25 '20 at 18:06