Unity UGUI技巧 之 区分鼠标点击UI还是场景物体
Unity UGUI技巧 之 区分鼠标点击UI还是场景物体。本节介绍,在Unity中,如何区分点击的对象是UI还是场景物体的简单案例,具体如下
工具/原料
Unity
EventSystem.IsPointerOverGameObject
一、知识要点
1、EventSystem.IsPointerO箪滹埘麽verGameObject:1)功能简述public boolIsPointerOverGameO芟鲠阻缒bject();public boolIsPointerOverGameObject(intpointerId);pointerId:Pointer (touch / mouse) ID.Is the pointer with the given ID over anEventSystemobject?If you use IsPointerOverGameObject() without a parameter, it points to the "left mouse button" (pointerId = -1); therefore when you use IsPointerOverGameObject for touch, you should consider passing a pointerId to it.2)使用举例using UnityEngine;using System.Collections;using UnityEngine.EventSystems;public class MouseExample : MonoBehaviour{ void Update() { // Check if the left mouse button was clicked if (Input.GetMouseButtonDown(0)) { // Check if the mouse was clicked over a UI element if (EventSystem.current.IsPointerOverGameObject()) { Debug.Log("Clicked on the UI"); } } }}
二、UGUI技巧 之 区分鼠标点击UI还是场景物体
1、打开Unity,新建一个工程,具体如下图

3、在工程中新建脚本“EventSystemsTest”,双击脚本或者右键“Open C# Project”打开脚本,具体如下图

5、“EventSystems哌囿亡噱Test”脚本的具体内容如下:using UnityEngine;using UnityEngine.EventSystems;public c造婷用痃lass EventSystemsTest : MonoBehaviour { // Update is called once per frame void Update () { if (Input.GetMouseButtonDown(0)) { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(ray, out hitInfo)) { if (EventSystem.current.IsPointerOverGameObject() == true) { Debug.Log(" the UI"); } else { Debug.Log(" the Cube"); hitInfo.collider.GetComponent<Renderer>().material.color = Color.red; } } } }}
6、脚本编译正确,回到Unity界面,在场景中,新建一个“GameObject”,把脚本“CursorTest”赋给“GameObject”,具体如下图


8、到此,《Unity UGUI技巧 之 区分鼠标点击UI还是场景物体》讲解结束,谢谢