Last active
October 12, 2017 09:59
-
-
Save ryo-ma/23d4d881867407265f716c22d82ea411 to your computer and use it in GitHub Desktop.
Unity Long Click and Short Click Component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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