Last Updated on 2021-10-28 by Clay
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:
It this way it is done. For other more complex functions, please refer the References.
References
- https://docs.unity3d.com/530/Documentation/ScriptReference/UI.Button.html
- https://docs.unity3d.com/2019.1/Documentation/ScriptReference/UI.Button-onClick.html
Thank you so much
You don’t know how much happy I am now..