Skip to content

Instantly share code, notes, and snippets.

@KickStudio
Created August 17, 2017 10:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KickStudio/60954baa061ed2b7a2b18ea2953f6d8b to your computer and use it in GitHub Desktop.
Save KickStudio/60954baa061ed2b7a2b18ea2953f6d8b to your computer and use it in GitHub Desktop.
Unity C# click and longPress
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class uGuiScript : MonoBehaviour, IPointerDownHandler, IPointerUpHandler {
public UnityEvent onLongPress = new UnityEvent();
public UnityEvent onClick = new UnityEvent();
[SerializeField]
private float longPressed;
[SerializeField]
private float diff;
private bool flgLongPressed = false;
private float timeElasped;
private Vector3 startPos;
private Vector3 nowPos;
private Vector3 endPos;
public bool pressed {
get;
private set;
}
void Update() {
nowPos = Input.mousePosition;
if(pressed) {
timeElasped += Time.deltaTime;
}
if (Mathf.Abs(startPos.x - nowPos.x) >= diff || Mathf.Abs(startPos.y - nowPos.y) >= diff) {
InitCount();
return;
}
if (longPressed < timeElasped && pressed == true) {
flgLongPressed = true;
onLongPress.Invoke();
InitCount();
}
}
public void OnPointerDown(PointerEventData eventData) {
startPos = eventData.position;
pressed = true;
}
public void OnPointerUp(PointerEventData eventData) {
endPos = eventData.position;
if(Mathf.Abs(startPos.x - endPos.x) >= diff || Mathf.Abs(startPos.y - endPos.y) >= diff) {
return;
}
if (flgLongPressed) {
flgLongPressed = false;
}else {
onClick.Invoke();
}
InitCount();
}
private void InitCount() {
pressed = false;
timeElasped = 0f;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment