I don't know how or if there is a built-in method for this. But you can easily build extending the button:
using UnityEngine.UI;
#if UNITY_EDITOR
using UnityEditor;
using UnityEditor.UI;
#endif
public class DwellTimeButton : Button
{
public float dwellTime = 0.5f;
public override void OnPointerEnter(PointerEventData pointerEventData)
{
base.OnPointerEnter(pointerEventData);
StartCoroutine (DwellTimeRoutine());
}
public override void OnPointerExit (PointerEventData pointerEventData)
{
base.OnPointerExit(pointerEventData);
StopAllCoroutines ();
}
private IEnumerator DwellTimeRoutine ()
{
yield return new WaitForSeconds (dwellTime);
onClick.Invoke();
}
#if UNITY_EDITOR
[CustomEditor (typeof (DwellTimeButton)]
private class DwellTimeButtonEditor : ButtonEditor
{
SerializedProperty dwellTime;
protected override void OnEnable()
{
base.OnEnable();
dwellTime = serializedObject.FindProperty("dwellTime");
}
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
serializedObject.Update();
EditorGUILayout.PropertyField(dwellTime);
serializedObject.ApplyModifiedProperties();
}
}
#endif
}
Replace a normal Unity Button with this component and set the desired dwellTime. It will then automatically invoke the onClick event after staying focused for the dwellTime.
As alternative without having to replace the Button everywhere you can simply attach this component additionally on every button:
using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
[RequireComponent(typeof(Button))]
public class DwellTimeButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler
{
[SerializeField] private Button button;
public float dwellTime = 0.5f;
private void Awake()
{
if (!button) button = GetComponent<Button>();
}
public void OnPointerEnter(PointerEventData pointerEventData)
{
button.OnPointerEnter(pointerEventData);
StartCoroutine(DwellTimeRoutine());
}
public void OnPointerExit(PointerEventData pointerEventData)
{
button.OnPointerExit(pointerEventData);
StopAllCoroutines();
}
private IEnumerator DwellTimeRoutine()
{
yield return new WaitForSeconds(dwellTime);
button.onClick.Invoke();
}
}
This does basically the same but invokes the onClick
and other events of the Button
component instead.
note: typed on smartphone but I hope the idea gets clear