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

2025-11-08 03:25:39

1、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");

            }

        }

    }

 }

1、打开Unity,新建一个工程,具体如下图

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

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

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

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

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

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

Unity UGUI技巧 之 区分鼠标点击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<Renderer>().material.color = Color.red;

                }

            }

        }

}

}

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

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

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

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

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

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

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢