本文主要是介绍UGUI鼠标事件绑定+鼠标长按,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
unity中鼠标事件的监听方式有很多,一般主要使用的是继承EventTrigger实现
EventTrigger中给我们提供了17种触发事件,这里不一一赘述,其中在游戏里经常使用的点击长按则没有。
比如在商店中购买,在背包中出售,技能加点,点击同一按钮时需要对按钮进行长按处理,来快速增加或减少。在unity 的ngui中有onpressed回调可以使用,但是在ugui中没有这种功能,就需要自己添加。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;public class UGUIEventListener : EventTrigger
{public delegate void VoidDelegate(GameObject go);public VoidDelegate onClick;public VoidDelegate onDown;public VoidDelegate onEnter;public VoidDelegate onExit;public VoidDelegate onUp;public VoidDelegate onSelect;public VoidDelegate onUpdateSelect;public VoidDelegate onLongPress; //长按按键public float interval = 1f; //长按按键判断间隔public float invokeInterval = 0.2f; //长按状态方法调用间隔private bool isPointDown = false;private float lastInvokeTime; //鼠标点击下的时间private float timer;static public UGUIEventListener Get(GameObject go){UGUIEventListener listener = go.GetComponent<UGUIEventListener>();if (listener == null) listener = go.AddComponent<UGUIEventListener>();return listener;}public override void OnPointerClick(PointerEventData eventData){if (onClick != null) onClick(gameObject);}public override void OnPointerDown(PointerEventData eventData){isPointDown = true;lastInvokeTime = Time.time;if (onDown != null) onDown(gameObject);}public override void OnPointerEnter(PointerEventData eventData){if (onEnter != null) onEnter(gameObject);}public override void OnPointerExit(PointerEventData eventData){isPointDown = false; //鼠标移出按钮时推出长按状态if (onExit != null) onExit(gameObject);}public override void OnPointerUp(PointerEventData eventData){isPointDown = false;if (onUp != null) onUp(gameObject);}public override void OnSelect(BaseEventData eventData){if (onSelect != null) onSelect(gameObject);}public override void OnUpdateSelected(BaseEventData eventData){if (onUpdateSelect != null) onUpdateSelect(gameObject);}private void Update(){if (isPointDown){if (Time.time-lastInvokeTime>interval){timer += Time.deltaTime;if (timer>invokeInterval){onLongPress.Invoke(gameObject);timer = 0;}}}}
}
使用方法如下:
using UnityEngine;public class Test : MonoBehaviour
{private GameObject image;// Use this for initializationprivate void Awake(){image = GameTool.FindTheChild(gameObject,"Image").gameObject;UGUIEventListener.Get(image).onLongPress = test; }public void test(GameObject go){Debug.Log("123");}}
这篇关于UGUI鼠标事件绑定+鼠标长按的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!