前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >unity3d:ugui 长按按钮

unity3d:ugui 长按按钮

作者头像
立羽
发布2023-08-24 14:22:13
2310
发布2023-08-24 14:22:13
举报
文章被收录于专栏:Unity3d程序开发Unity3d程序开发
代码语言:javascript
复制
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.Events;

public class RepeatButton : MonoBehaviour, IPointerDownHandler, IPointerUpHandler, IPointerExitHandler {

	public bool invokeOnce = false;//是否只调用一次
	private bool hadInvoke = false;//是否已经调用过

	public float interval = 0.1f;//按下后超过这个时间则认定为"长按"
	private bool isPointerDown = false;
	private float recordTime;

	public UnityEvent onPress = new UnityEvent();//按住时调用
	public UnityEvent onRelease = new UnityEvent();//松开时调用

    public static RepeatButton Get(Transform trans)
    {
        if (trans.GetComponent<RepeatButton>() == null)
        {
            trans.gameObject.AddComponent<RepeatButton>();
        }
        return trans.GetComponent<RepeatButton>();
    }
    void Update () 
	{
		if (invokeOnce && hadInvoke) return;
		if (isPointerDown)
		{
			if ((Time.time - recordTime) > interval)
			{
				onPress.Invoke();
				hadInvoke = true;
                recordTime = Time.time;
            }
		}
	}

	public void OnPointerDown(PointerEventData eventData)
	{
		isPointerDown = true;
		recordTime = Time.time;
	}

	public void OnPointerUp(PointerEventData eventData)
	{
		isPointerDown = false;
		hadInvoke = false;
		onRelease.Invoke();
	}

	public void OnPointerExit(PointerEventData eventData)
	{
		isPointerDown = false;
		hadInvoke = false;
		onRelease.Invoke();
	}
}

如何使用

代码语言:javascript
复制
RepeatButton.Get(m_trans.Find("BtnPar/BtnShang")).onPress.AddListener(()=> { OnBtnTianChe(EnTianCheDir.Shang); });
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018-05-30,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档