2

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!!
0

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();
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.