赞
踩
问题产生的背景:我们在开发一些游戏的时候,比如捕鱼或者射击类游戏,鼠标(手指)点击会发射子弹。但是当我们点击在UI上面的时候,我们不希望触发射线检测,怎么解决,关键代码就是
EventSystem.current.IsPointerOverGameObject() 如果当前鼠标在 ui 上返回true 否则返回false。
如下代码所示:
- using UnityEngine;
- using System.Collections;
- using UnityEngine.EventSystems;
-
- public class MenuClick : MonoBehaviour {
-
- // Update is called once per frame
- void Update () {
-
- if (Input.GetMouseButtonDown(0))
- {
- OnClick();
- }
- }
-
- void OnClick ()
- {
- //从主相机到鼠标点发射一条射线
- Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
- //接受射线返回的碰撞信息
- RaycastHit hitInfo;
- //如果射线碰撞到东西
-
- if (Physics.Raycast(ray, out hitInfo) && !EventSystem.current.IsPointerOverGameObject())
- {
- Debug.DrawLine(ray.origin, hitInfo.point);//划出射线,只有在scene视图中才能看到
- GameObject gameObj = hitInfo.collider.gameObject;
- Debug.Log("click object name is " + gameObj.name);
- }
- }
- }

自己运行,查看效果即可。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。