郑州unity3d培训 UGUI长按监测的两种方法
来源:
奇酷教育 发表于:
郑州unity3d培训 UGUI长按监测的两种方法,奇酷(www qikuedu com)老师总结两种办法如下: 简单的demo,随便建几个UI,把
郑州unity3d培训 UGUI长按监测的两种方法,
奇酷(www.qikuedu.com)老师总结两种办法如下:
简单的demo,随便建几个UI,把脚本拖到任意物体,按1秒钟后有响应事件。以下脚本可避免ScrollView失效,以及重叠UI穿透选择。
VR1VJ" src="http://uploadfile.qikuedu.com/2019/0319/20190319110022305.jpg" style="width: 480px; height: 270px;" />
方法一:使用EventSystems,适合场景中简单的UI操作
using UnityEngine.EventSystems;
public class RyanPressTest : MonoBehaviour {
Vector3 lastMousePose;
EventSystem m_EventSystem;
float curT = 0;
// 是否已经被选择
bool isPressed = false;
void Start(){
m_EventSystem = FindObjectOfType();
}
void Update () {
if(Input.GetMouseButtonDown(0)){
lastMousePose = Input.mousePosition;
}
if (Input.GetMouseButton(0) && !isPressed && lastMousePose == Input.mousePosition)
{
curT += Time.deltaTime;
// 长按1秒
if(curT >= 1f){
Debug.Log(m_EventSystem.currentSelectedGameObject + " was pressed.");
isPressed = true;
}
}
if(Input.GetMouseButtonUp(0)){
isPressed = false;
curT = 0;
}
}
}
方法二:使用射线,适用于鼠标一下选择多个UI的复杂场景
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class RyanPressTest : MonoBehaviour {
Vector3 lastMousePose;
GraphicRaycaster m_Raycaster;
PointerEventData m_PointerEventData;
float curT = 0;
// 是否已经被选择
bool isPressed = false;
void Start(){
m_Raycaster = FindObjectOfType ();
}
void Update () {
if(Input.GetMouseButtonDown(0)){
lastMousePose = Input.mousePosition;
}
if (Input.GetMouseButton(0) && !isPressed && lastMousePose == Input.mousePosition)
{
curT += Time.deltaTime;
m_PointerEventData = new PointerEventData(null);
m_PointerEventData.position = lastMousePose;
List results = new List();
m_Raycaster.Raycast(m_PointerEventData, results);
// 长按1秒
if(results.Count > 0 && curT >= 1f){
// 当有多个重叠UI,results会返回所有被射线穿透的UI数组,一般我们只需要最上面的那个UI
Debug.Log(results[0].gameObject + " was pressed.");
isPressed = true;
}
}
if(Input.GetMouseButtonUp(0)){
isPressed = false;
curT = 0;
}
}
}
其实EventTrigger也能监测长按,但用了它ScrollView就失效了,还是用上面两种方法比较通。