I made my own class that inherits from button and has an OnHold
event. It seems to work ok but I'm wondering if I can improve it or if you can spot any glaring mistakes that I made.
Here is the code:
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
using UnityEngine.Events;
[AddComponentMenu("UI/Hold Button")]
public class HoldButton : Button
{
private bool isBeingPressed;
private float currTime;
private static float TimeMax = 2;
private bool startTimer;
public ButtonHoldEvent onHold { get; set; }
public override void OnPointerDown(PointerEventData eventData)
{
startTimer = true;
currTime = 0;
}
public override void OnPointerUp(PointerEventData eventData)
{
startTimer = false;
currTime = 0;
isBeingPressed = false;
}
void Update()
{
if(startTimer)
{
currTime += Time.deltaTime;
if(currTime >= TimeMax)
{
isBeingPressed = true;
}else
{
isBeingPressed = false;
}
}
if (isBeingPressed)
{
onHold.Invoke();
}
}
public class ButtonHoldEvent : UnityEvent
{
public ButtonHoldEvent() : base()
{
}
}
}
isBeingPressed
is a boolean variable you can simply give it the value of a specific condition, instead of checkingif(currTime >= TimeMax)
then setting the value ofisBeingPressed
to true, You can just doisBeingPressed = currTime >= TimeMax
\$\endgroup\$