Holding U.I. Button For Longer Jumps

Okay so I’ve ran into a quick problem. So at first my game had movement to where however long u click and hold anywhere on the screen he jumps, and then comes down, through scripts. But having the player clicked anywhere on the screen brought complications, so now I made a U.I. button. Problem is now, when I try “OnClick” it doesnt count when your “Holding” the button down. Nor does "Event Trigger on Pointer Down.

So is this even possible through U.I. buttons?

I would call a function or a Coroutine in which i count time and apply whatever when released (you can set a release event) :slight_smile:

1 Like

How would I go about doing that? Sorry I’m new to scripting.

Something like this should work I think.

This class will listen for OnPointerDown and OnPointerUp, and will run a coroutine between the two events.

There are UnityEvents that fire at the correct times so you can configure behavior in the inspector or add code to the spots i commented:

using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.Events;

public class PressAndHold : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
    // events that show up in the inspector
    public UnityEvent OnPress;
    public UnityEvent OnHold;
    public UnityEvent OnRelease;

    // true if the user is holding down the pointer
    private bool holding;

    public void OnPointerDown(PointerEventData data)
    {
        holding = true;
        OnPress.Invoke();

        // do any custom "OnPress" behavior here

        StartCoroutine(LoopWhileHolding());
    }

    public void OnPointerUp(PointerEventData data)
    {
        holding = false;
        OnRelease.Invoke();

        // do any custom "OnRelease" behavior here

    }

    // loops until OnPointerUp is called
    private IEnumerator LoopWhileHolding()
    {
        while(holding)
        {
            OnHold.Invoke();

            // do any custom "OnHold" behavior here

            yield return null; // makes the loop wait until next frame to continue
        }
    }
}
2 Likes

Thanks guys! Much appreciated! I’m going to try this out and will be sure to get back to you to let you know of my progress.

Just wanted to come back and give a big thank you. It worked great guys. I had some trouble at first, but after making it its own script and putting it on the same button and messing with it through the inspector, it worked great! Thank you!!

1 Like