鼠標(biāo)穿透UI問(wèn)題

一、在做項(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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容