鄭州unity3d培訓(xùn) UGUI長(zhǎng)按監(jiān)測(cè)的兩種方法
來(lái)源:
奇酷教育 發(fā)表于:
鄭州unity3d培訓(xùn) UGUI長(zhǎng)按監(jiān)測(cè)的兩種方法,奇酷(www qikuedu com)老師總結(jié)兩種辦法如下: 簡(jiǎn)單的demo,隨便建幾個(gè)UI,把
鄭州unity3d培訓(xùn) UGUI長(zhǎng)按監(jiān)測(cè)的兩種方法,
奇酷(noah-r.com)老師總結(jié)兩種辦法如下:
簡(jiǎn)單的demo,隨便建幾個(gè)UI,把腳本拖到任意物體,按1秒鐘后有響應(yīng)事件。以下腳本可避免ScrollView失效,以及重疊UI穿透選擇。
VR1VJ" src="http://uploadfile.qikuedu.com/2019/0319/20190319110022305.jpg" style="width: 480px; height: 270px;" />
方法一:使用EventSystems,適合場(chǎng)景中簡(jiǎn)單的UI操作
using UnityEngine.EventSystems;
public class RyanPressTest : MonoBehaviour {
Vector3 lastMousePose;
EventSystem m_EventSystem;
float curT = 0;
// 是否已經(jīng)被選擇
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;
// 長(zhǎng)按1秒
if(curT >= 1f){
Debug.Log(m_EventSystem.currentSelectedGameObject + " was pressed.");
isPressed = true;
}
}
if(Input.GetMouseButtonUp(0)){
isPressed = false;
curT = 0;
}
}
}
方法二:使用射線,適用于鼠標(biāo)一下選擇多個(gè)UI的復(fù)雜場(chǎng)景
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class RyanPressTest : MonoBehaviour {
Vector3 lastMousePose;
GraphicRaycaster m_Raycaster;
PointerEventData m_PointerEventData;
float curT = 0;
// 是否已經(jīng)被選擇
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);
// 長(zhǎng)按1秒
if(results.Count > 0 && curT >= 1f){
// 當(dāng)有多個(gè)重疊UI,results會(huì)返回所有被射線穿透的UI數(shù)組,一般我們只需要最上面的那個(gè)UI
Debug.Log(results[0].gameObject + " was pressed.");
isPressed = true;
}
}
if(Input.GetMouseButtonUp(0)){
isPressed = false;
curT = 0;
}
}
}
其實(shí)EventTrigger也能監(jiān)測(cè)長(zhǎng)按,但用了它ScrollView就失效了,還是用上面兩種方法比較通。