鼠标穿透UI问题
2018-04-25 本文已影响0人
李昀熹1112
一、在做项目时,经常会遇到点击按钮后,会触发在项目场景中的物体

二、下面就开始带你来解决这个小问题
1、首先新建项目,在Hierarchy中,创建Plane,Sphere,Button,如下图

2、在Project中,创建脚本命名为【PointerPenetrate】,然后双击打开,这里就直接贴代码啦...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PointerPenetrate : MonoBehaviour {
public GameObject sphere;
void Update()
{
//按下鼠标左键
if (Input.GetMouseButtonDown(0))
{
//检测是否是UI
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("点击的是UI");
}
else
{
Debug.Log("点击的是3D物体");
//射线检测
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//定义射线检测器
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
//如果当前射线检测到的对象的名字是cube
if (hitInfo.collider.name == "Sphere")
{
//改变cube的颜色,随机一个颜色
sphere.GetComponent<MeshRenderer>().material.color =
new Color(Random.value, Random.value, Random.value, 1.0f);
}
}
}
}
//打包成安卓项目后,判断是UI还是3D物体
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{
Debug.Log("点击的是UI");
}
else
{
Debug.Log("点击的是3D物体");
}
}
}
}
3、然后将将脚本挂载在【Canvas】上,在把【Sphere】拖入脚本中

4、最后运行我们来看看结果
