多语言展示
当前在线:129今日阅读:2今日分享:38

Unity UGUI技巧 之 区分鼠标点击UI还是场景物体

Unity UGUI技巧 之 区分鼠标点击UI还是场景物体。本节介绍,在Unity中,如何区分点击的对象是UI还是场景物体的简单案例,具体如下
工具/原料
1

Unity

2

EventSystem.IsPointerOverGameObject

一、知识要点

EventSystem.IsPointerOverGameObject:1)功能简述public bool IsPointerOverGameObject();public bool IsPointerOverGameObject(int pointerId);pointerId:Pointer (touch / mouse) ID.Is the pointer with the given ID over an EventSystem object?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,新建一个工程,具体如下图

2

在场景中,新建一个“Cube”和“Button”,调整各自大小及布局,具体如下图

3

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

4

在脚本“EventSystemsTest”上编写代码,在Update函数里,按下鼠标左键,发射一条射线,然后使用“EventSystem.current.IsPointerOverGameObject()”的返回值来判断是碰到UI还是场景物体,其中返回TRUE是碰到UI,具体代码和代码说明图下图

5

“EventSystemsTest”脚本的具体内容如下:using UnityEngine;using UnityEngine.EventSystems;public class 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().material.color = Color.red;                }            }        } }}

6

脚本编译正确,回到Unity界面,在场景中,新建一个“GameObject”,把脚本“CursorTest”赋给“GameObject”,具体如下图

7

运行场景,在游戏视图中,按下鼠标左键,首先是点击UI的效果,然后是点击场景物体的效果,控制台Console打印,具体如下图

8

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

注意事项

您的支持,是我们不断坚持知识分享的动力,若帮到您,还请帮忙投票有得;若有疑问,请留言

推荐信息