本段主要是为了学习记录,在Unity中怎么给一个BoxCollider添加事件脚本,以点击事件为例,并且,添加物体事件一些必要的前提。
首先是射线检测部分,如下类 AddEeventMonoTest.cs, 其中初始化阶段准备了 必要的一些组件,相机的射线检测组件PhysicsRaycaster,以及事件系统的两个组件(EventSystem,StandaloneInputModule),但是事件相关的这俩组件未必需要绑定到Camera上,任意激活对象上都行。
如下具体实现是给一个Cube添加点击事件的逻辑:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
/// <summary>
/// 给指定的BoxCollider添加点击事件
/// </summary>
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<PhysicsRaycaster>() == null)
{
gameObject.AddComponen