Reputation: 323
How to detect touches and long touches on buttons in unity for android? I have already tried this function but it returns true if i touch any place on screen:
bool checkTouch()
{
for(int i = 0; i < Input.touchCount; i++)
{
TouchPhase tp = Input.GetTouch(i).phase;
if(tp == TouchPhase.Began || tp == TouchPhase.Ended || tp == TouchPhase.Stationary)
return true;
}
return false;
}
Upvotes: 0
Views: 58
Reputation: 4283
One way to achieve Buttons that allow that, is to create your own button, implementing the necessary interfaces like IPointerDownHandler, IPointerUpHandler
.
That way you could manage how will the button act, here is an example:
using UnityEngine;
using UnityEngine.EventSystems;
public class LongClickButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
private bool pointerDown;
private float pointerDownTimer;
[SerializeField]
private float requiredHoldTime;
public void OnPointerDown(PointerEventData eventData)
{
pointerDown = true;
Debug.Log("OnPointerDown");
}
public void OnPointerUp(PointerEventData eventData)
{
Reset();
Debug.Log("OnPointerUp");
}
private void Update()
{
if (pointerDown)
{
pointerDownTimer += Time.deltaTime;
if (pointerDownTimer >= requiredHoldTime)
{
//do your LongClick stuff
Debug.Log("LongClick");
Reset();
}
}
}
private void Reset()
{
pointerDown = false;
pointerDownTimer = 0;
}
}
Remember to attach the script to a GameObject that can be interactable
, like an Image
.
Upvotes: 1