Skip to content

Instantly share code, notes, and snippets.

@ryo-ma
Last active October 12, 2017 09:59
Show Gist options
  • Select an option

  • Save ryo-ma/23d4d881867407265f716c22d82ea411 to your computer and use it in GitHub Desktop.

Select an option

Save ryo-ma/23d4d881867407265f716c22d82ea411 to your computer and use it in GitHub Desktop.
Unity Long Click and Short Click Component
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
public class ClickEvent : MonoBehaviour
{
[SerializeField]
private UnityEvent onLongClick;
[SerializeField]
private UnityEvent onClick;
[SerializeField]
private float clickTime = 2.0f;
private bool isInvoked = false;
private float currentClickTime = 0f;
public bool IsPress
{
get;
set;
}
// Use this for initialization
void Start()
{
EventTrigger trigger = gameObject.AddComponent<EventTrigger>();
trigger.triggers = new List<EventTrigger.Entry>();
EventTrigger.Entry downEntry = new EventTrigger.Entry();
downEntry.eventID = EventTriggerType.PointerDown;
downEntry.callback.AddListener((x) => { this.OnDown(); });
trigger.triggers.Add(downEntry);
EventTrigger.Entry upEntry = new EventTrigger.Entry();
upEntry.eventID = EventTriggerType.PointerUp;
upEntry.callback.AddListener((x) => { this.OnUp(); });
trigger.triggers.Add(upEntry);
}
// Update is called once per frame
void Update()
{
if (this.IsPress)
{
this.currentClickTime += Time.deltaTime;
}
}
public void OnDown()
{
this.IsPress = true;
}
public void OnUp()
{
if (this.currentClickTime > this.clickTime)
{
this.onLongClick.Invoke();
}
else
{
this.onClick.Invoke();
}
this.IsPress = false;
this.currentClickTime = 0f;
this.isInvoked = false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment