Aditya Nambidi
Aditya Nambidi

Reputation: 111

How to detect if the UI button has been released? Unity - C#

im using unity. I have made a button in the canvas and when it is clicked the bool becomes true. I used the OnClick function for this. now how do i detect when the button is released because i want to make the bool false when the button is released.

Upvotes: 2

Views: 3251

Answers (2)

VK321
VK321

Reputation: 5963

if you want to get refrence like unity's default button you can use this code

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.Serialization;

public class YourButton : MonoBehaviour, IPointerDownHandler, 
IPointerUpHandler
{
    private bool _isPressed = false;
    [System.Serializable]
    public class ButtonReleasedEvent : UnityEvent {}

    // Event delegates triggered on mouse up.
    [FormerlySerializedAs("onMouseUp")]
    [SerializeField]
    private ButtonReleasedEvent _onReleased = new ButtonReleasedEvent();

    public void OnPointerDown(PointerEventData eventData)
    {
        _isPressed = true;
    }
    public void OnPointerUp(PointerEventData eventData)
    {
        if (_isPressed)
        {
            _isPressed = false;
            _onReleased.Invoke();
        }
    }
}

Upvotes: 0

luvjungle
luvjungle

Reputation: 1066

You can use Unity Events System. First, remove all code for onClick It will be handled by events. Then add this script on Button gameObject.

using UnityEngine;
using UnityEngine.EventSystems;

public class Events : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    private bool myBool;
    
    public void OnPointerDown(PointerEventData eventData)
    {
        myBool = true;
        Debug.Log("pointer down");
    }

    public void OnPointerUp(PointerEventData eventData)
    {
        myBool = false;
        Debug.Log("pointer up");
    }
}

Also you can use IPointerClickHandler interface, maybe it will suit your needs better.

Upvotes: 3

Related Questions