Unity3D为3D物体添加点击事件

1.相机添加脚本《ClickEvent》:

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

public class ClickEvent : MonoBehaviour {

    public GameObject[] cube1; //3D物体集合

    private void Start()
    {
        //为相机添加3个组件
        if (this.gameObject.GetComponent() == null) {
            gameObject.AddComponent();
        }
        if (this.gameObject.GetComponent() == null)
        {
            this.gameObject.AddComponent();
        }

        if (this.gameObject.GetComponent() == null)
        {
            gameObject.AddComponent();
        }
        
        //为3D物体添加点击事件
        for (int i = 0; i < cube1.Length; i++)
        {
            AddObjectClickEvent(cube1[i]);
        }
    }

    public void AddObjectClickEvent(GameObject itemObject) {
        var box = itemObject.GetComponent();
        if (box == null)
        {
            box = itemObject.AddComponent();
        }
        
        // ThreeD_Object为3D物体挂载的脚本
        var item = itemObject.GetComponent();
        if (item == null)
        {
            item = itemObject.AddComponent();
        }
            
        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);
    }
}

2.为3D物体添加脚本《Threed_Object》:

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

public class CubeEventItemBind : MonoBehaviour {


    public void OnClickCubeItem(UnityEngine.EventSystems.BaseEventData data = null)
    {
        Debug.Log("点击了" + transform.name);
        //点击对应事件
    }
}

 

你可能感兴趣的:(Unity3D,Unity3D开发)