Unity | 工具类-按钮长按

 1.继承Button,利用OnPointerDown和OnPointerUp来实现长按监听。

using UnityEngine;
using UnityEngine.Events;
using UnityEngine.EventSystems;
using UnityEngine.UI;


public class ButtonPress : Button
{
    public bool isPointerDown = false;
    private float timePressStarted;
    private float durationThreshold = 0.2f; // 长按的阈值时间

    public UnityEvent OnPress = new UnityEvent(); // 长按事件
    public UnityEvent OnPressEnd = new UnityEvent(); // 长按结束事件

    private void Update()
    {
        if (isPointerDown)
        {
            if (Time.time - timePressStarted > durationThreshold) // 检查是否超过阈值
            {
                OnPress.Invoke(); 
            }
        }
    }

    public override void OnPointerDown(PointerEventData eventData)
    {
        base.OnPointerDown(eventData); // 调用基类的方法
        if (eventData.button != PointerEventData.InputButton.Left)
            return;

        timePressStarted = Time.time;
        isPointerDown = true;
    }

    public override void OnPointerUp(PointerEventData eventData)
    {
        base.OnPointerUp(eventData); // 调用基类的方法
        isPointerDown = false;
        OnPressEnd.Invoke();
    }
}

2.左右两个按钮添加ButtonPress组件,实现按钮长按时控制Cube左右移动

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestMyButton : MonoBehaviour
{
    public GameObject uiButtonCanvas;
    public GameObject cube;
    bool isLeft = false;
    bool isRight = false;
    // Start is called before the first frame update
    void Start()
    {

        ButtonPress leftButton = uiButtonCanvas.transform.Find("leftButton").GetComponent<ButtonPress>();
        leftButton.OnPress.AddListener(() =>
        {
            isLeft = true;

        });
        leftButton.OnPressEnd.AddListener(() =>
        {
            isLeft = false;
        });
        ButtonPress rightButton = uiButtonCanvas.transform.Find("rightButton").GetComponent<ButtonPress>();
        rightButton.OnPress.AddListener(() =>
        {
            isRight = true;
        });
        rightButton.OnPressEnd.AddListener(() =>
        {
            isRight = false;
        });
    }

    // Update is called once per frame
    void Update()
    {
        if (isLeft)
        {
            cube.transform.localPosition += Vector3.left * 0.1f;
        }
        else if (isRight)
        {
            cube.transform.localPosition += Vector3.right * 0.1f;

        }
        else
        {
            cube.transform.localPosition += Vector3.forward * 0.1f;

        }
    }
}

猜你喜欢

转载自blog.csdn.net/weixin_39766005/article/details/137071890