Skip to content

[Unity] Button Event: OnPointerDown() and OnPointerUp()

The button component is built in the Unity UI layout, so we can simply to create the function to trigger the button event when user clicking. But if it is necessary to set the events of the button "pressed" and "released" separately, we can write a script to inherit the Button class, and override the OnPointerDown() event and OnPointerUp() event.


Example

First we need to create a Button component, and put it on the window center.


Then we attach the script myButtonEvent.cs to Button. The script will get the Text child component, and change the text when the button pressed.

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

public class myButtonEvent : Button
{
    // Button is Pressed
    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData);
        gameObject.GetComponentInChildren<Text>().text = "Pressed";
    }

    // Button is released
    public override void OnPointerUp(PointerEventData eventData)
    {
        base.OnPointerUp(eventData);
        gameObject.GetComponentInChildren<Text>().text = "Released";

    }
}


Output:

Pressed
Released

It this way it is done. For other more complex functions, please refer the References.


References


Read More

Tags:

2 thoughts on “[Unity] Button Event: OnPointerDown() and OnPointerUp()”

Leave a Reply