欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

unity 3d模型添加Onclick事件

程序员文章站 2022-06-16 09:24:58
...

1、给camera添加下方的 EventUtil 的脚本

EventUtil 代码:

using System.Collections; 
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
 public class EventUtil : MonoBehaviour { 
    void Start()
    {  
    if (this.gameObject.GetComponent<PhysicsRaycaster>() == null)
    {
        gameObject.AddComponent<PhysicsRaycaster>();
    }

    if (this.gameObject.GetComponent<EventSystem>() == null)
    {
        this.gameObject.AddComponent<EventSystem>();
    }

    if (this.gameObject.GetComponent<StandaloneInputModule>() == null)
    {
        gameObject.AddComponent<StandaloneInputModule>();
    }
}

/// <summary>
/// 添加组件,BoxCollider,CubeEventItemBind,EventTrigger 和事件函数
/// </summary>
/// <param name="itemObject">需要添加的物体</param> 
/// <param name="unityAction">需要添加的事件</param>
public static  void AddClickEvent(GameObject itemObject, UnityAction<BaseEventData> unityAction)
{
    var box = itemObject.GetComponent<BoxCollider>();
    if (box == null)
    {
        box = itemObject.AddComponent<BoxCollider>();
    }

    EventTrigger trigger = itemObject.GetComponent<EventTrigger>();
    if (trigger == null)
        trigger = itemObject.AddComponent<EventTrigger>();

    EventTrigger.Entry entry = new EventTrigger.Entry();
    entry.eventID = EventTriggerType.PointerClick;
    UnityAction<BaseEventData> click = unityAction;
    entry.callback.AddListener(click);

    trigger.triggers.Clear();
    trigger.triggers.Add(entry);
} 
}  

调用代码

//go 是被点击的物体
EventUtil.AddClickEvent(go, delegate(UnityEngine.EventSystems.BaseEventData data) 
{
         Debug.Log(go.name);
});

本文转载自https://www.jianshu.com/p/58d27230a1ad