一、在做項(xiàng)目時(shí),經(jīng)常會(huì)遇到點(diǎn)擊按鈕后,會(huì)觸發(fā)在項(xiàng)目場(chǎng)景中的物體

image.png
二、下面就開(kāi)始帶你來(lái)解決這個(gè)小問(wèn)題
1、首先新建項(xiàng)目,在Hierarchy中,創(chuàng)建Plane,Sphere,Button,如下圖

image.png
2、在Project中,創(chuàng)建腳本命名為【PointerPenetrate】,然后雙擊打開(kāi),這里就直接貼代碼啦...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class PointerPenetrate : MonoBehaviour {
public GameObject sphere;
void Update()
{
//按下鼠標(biāo)左鍵
if (Input.GetMouseButtonDown(0))
{
//檢測(cè)是否是UI
if (EventSystem.current.IsPointerOverGameObject())
{
Debug.Log("點(diǎn)擊的是UI");
}
else
{
Debug.Log("點(diǎn)擊的是3D物體");
//射線檢測(cè)
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//定義射線檢測(cè)器
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
//如果當(dāng)前射線檢測(cè)到的對(duì)象的名字是cube
if (hitInfo.collider.name == "Sphere")
{
//改變cube的顏色,隨機(jī)一個(gè)顏色
sphere.GetComponent<MeshRenderer>().material.color =
new Color(Random.value, Random.value, Random.value, 1.0f);
}
}
}
}
//打包成安卓項(xiàng)目后,判斷是UI還是3D物體
if (Input.touchCount > 0 && Input.GetTouch(0).phase == TouchPhase.Began)
{
if (EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId))
{
Debug.Log("點(diǎn)擊的是UI");
}
else
{
Debug.Log("點(diǎn)擊的是3D物體");
}
}
}
}
3、然后將將腳本掛載在【Canvas】上,在把【Sphere】拖入腳本中

image.png
4、最后運(yùn)行我們來(lái)看看結(jié)果

20180425_115804 (1).gif