Unity给3D物体添加点击事件脚本

本段主要是为了学习记录,在Unity中怎么给一个BoxCollider添加事件脚本,以点击事件为例,并且,添加物体事件一些必要的前提。

首先是射线检测部分,如下类 AddEeventMonoTest.cs, 其中初始化阶段准备了 必要的一些组件,相机的射线检测组件PhysicsRaycaster,以及事件系统的两个组件(EventSystem,StandaloneInputModule),但是事件相关的这俩组件未必需要绑定到Camera上,任意激活对象上都行。

如下具体实现是给一个Cube添加点击事件的逻辑:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;

/// 
/// 给指定的BoxCollider添加点击事件
/// 
public class AddEeventMonoTest : MonoBehaviour
{

    public GameObject targetGameObject;

    // Use this for initialization
    void Start()
    {
        targetGameObject = GameObject.Find("Cube");

        //Camera上必须要有 PhysicsRaycaster,EventSystem,StandaloneInputModule 组件
        if (this.gameObject.GetComponent() == null)
        {
            gameObject.AddComponent();
        }

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

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

    /// 
    /// 添加组件,BoxCollider,CubeEventItemBind,EventTrigger 和事件函数
    /// 
    /// 
    public void AddObjectClickEvent(GameObject itemObject)
    {
        var box = itemObject.GetComponent();
        if (box == null)
        {
            box = itemObject.AddComponent();
        }

        var item = itemObject.GetComponent();
        if (item == null)
            item = itemObject.AddComponent();
        item.paramStr = "哈哈";

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

        EventTrigger.Entry entry = new EventTrigger.Entry();
        entry.eventID = EventTriggerType.PointerClick;
        UnityEngine.Events.UnityAction click = new UnityEngine.Events.UnityAction(item.OnClickCubeItem);
        entry.callback.AddListener(click);

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

    private void OnGUI()
    {
        if (GUILayout.Button("给 GameObject=" + targetGameObject + ",添加点击事件!!"))
        {
            Debug.Log("给 " + targetGameObject + ",添加事件");
            AddObjectClickEvent(targetGameObject);
        }
    }
}

然后,Cube上负责接收事件的脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// 
/// function:具体  cube上 的点击响应事件
/// 
public class CubeEventItemBind : MonoBehaviour {

    public string paramStr = "";

    public void OnClickCubeItem(UnityEngine.EventSystems.BaseEventData data = null)
    {
        Debug.Log("点击了cube tran=" + transform.name + ",paramStr=" + paramStr);
    }
}

gif是运行效果截图
这里写图片描述

附上具体的资源包的github地址↓↓↓ :)
点击这里

你可能感兴趣的:(Unity,C#,Unity学习总结)