unity 如何判斷鼠標是否在哪個UI上(兩種方法)
第一種
可以得到UI,再根據(jù)名字判斷是不是自己自己要點擊的UI
其中參數(shù)canvas拖入此UI的canvas
/// <summary>
/// 獲取鼠標停留處UI
/// </summary>
/// <param name="canvas"></param>
/// <returns></returns>
public GameObject GetOverUI(GameObject canvas)
{
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = Input.mousePosition;
GraphicRaycaster gr = canvas.GetComponent<GraphicRaycaster>();
List<RaycastResult> results = new List<RaycastResult>();
gr.Raycast(pointerEventData, results);
if (results.Count != 0)
{
return results[0].gameObject;
}
return null;
}
第二種就簡單了
rect 為要判斷的那個UI的RectTransform
bool isUI = RectTransformUtility.RectangleContainsScreenPoint(rect, Input.mousePosition)
補充:Unity中判斷鼠標或者手指是否點擊在UI上(UGUI)
在Unity場景中,有時UI和游戲角色都需要響應(yīng)觸摸事件,如果同時響應(yīng)可能就會出現(xiàn)點擊UI的時候影響到了游戲角色。所以我們需要對所點擊到的東西做判斷,這里使用UGUI系統(tǒng)自帶的方法和射線檢測的方式,判斷是否點擊到UI上:
第一種方法,直接在Update中判斷:
void Update()
{
//判斷是否點擊UI
if (Input.GetMouseButtonDown(0) || (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began))
{
//移動端
if (Application.platform == RuntimePlatform.Android ||
Application.platform == RuntimePlatform.IPhonePlayer)
{
int fingerId = Input.GetTouch(0).fingerId;
if (EventSystem.current.IsPointerOverGameObject(fingerId))
{
Debug.Log("點擊到UI");
}
}
//其它平臺
else
{
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("點擊到UI");
}
}
}
第二種方式:射線檢測
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class NewBehaviourScript : MonoBehaviour
{
// Update is called once per frame
void Update()
{
//移動端
if (Application.platform == RuntimePlatform.Android ||
Application.platform == RuntimePlatform.IPhonePlayer)
{
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
if (IsPointerOverGameObject(Input.GetTouch(0).position))
{
Debug.Log("點擊到UI");
}
}
}
//其它平臺
else
{
if(Input.GetMouseButtonDown(0))
{
if (IsPointerOverGameObject(Input.mousePosition))
{
Debug.Log("點擊到UI");
}
}
}
}
/// <summary>
/// 檢測是否點擊UI
/// </summary>
/// <param name="mousePosition"></param>
/// <returns></returns>
private bool IsPointerOverGameObject(Vector2 mousePosition)
{
//創(chuàng)建一個點擊事件
PointerEventData eventData = new PointerEventData(EventSystem.current);
eventData.position = mousePosition;
List<RaycastResult> raycastResults = new List<RaycastResult>();
//向點擊位置發(fā)射一條射線,檢測是否點擊UI
EventSystem.current.RaycastAll(eventData, raycastResults);
if (raycastResults.Count > 0)
{
return true;
}
else
{
return false;
}
}
}
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。如有錯誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章
DevExpress實現(xiàn)GridControl單元格編輯驗證的方法
這篇文章主要介紹了DevExpress實現(xiàn)GridControl單元格編輯驗證的方法,很實用的功能,需要的朋友可以參考下2014-08-08
C#實現(xiàn)TreeView節(jié)點拖拽的方法
這篇文章主要介紹了C#實現(xiàn)TreeView節(jié)點拖拽的方法,涉及C#針對TreeView節(jié)點的動態(tài)添加及移除技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-09-09

