Reputation: 111
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
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
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