Unity實現模型點擊事件的方法

模型點擊事件監聽

觸發模型點擊事件的必要條件

需要觸發模型點擊事件的模型身上必須要掛載Collider 組件

方法一

通過 OnMouseDown 函數監聽(隻能在PC端有效)

1.在Hierarchy 面板中右鍵,點擊 3D Object->Cube 按鈕,創建一個 Cube 模型

2.新建一個腳本,命名為“Test.cs”(代碼如下)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Test2 : MonoBehaviour
{
    private void OnMouseDown()
    {
        Debug.Log("OnMouseDown");
    }
}

3.將 Test.cs 腳本,掛載到Cube 上,(運行,點擊模型後結果如下)

方法二

通過射線檢測事件監聽(所有平臺都可以執行,推薦使用這種方式)

1.新建一個腳本,命名為“ColliderEvent.cs”(代碼如下)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class ColliderEvent : MonoBehaviour
{
    private void Update()
    {
       if(Input.GetMouseButtonDown(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            RaycastHit hitInfo;
            if(Physics.Raycast(ray,out hitInfo))
            {
                Debug.Log(hitInfo.transform.name);
            }
        }
    }
}

2.將 ColliderEvent 腳本,掛載到 Main Camera 上,(運行,點擊模型後結果如下)

方法三

使用Event Trigger 組件

1.場景內添加Event System

2.給 Main Camera 添加 Physics Raycaster 組件

3.新建一個腳本,命名“Test2.cs”。(代碼如下)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class Test2 : MonoBehaviour
{
    private void OnMouseDown()
    {
        Debug.Log("OnMouseDown");
    }
}

4.在Cube 模型上添加EvenTrigger組件

5.點擊 Add New Event Type 按鈕,選擇事件類型,並將 Test2.cs 腳本,添加到場景中,選擇點擊後觸發的函數為 OnClickModel()

6.運行結果如下

到此這篇關於Unity模型點擊事件的文章就介紹到這瞭,更多相關Unity模型點擊事件內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: