1. 程式人生 > >【UGUI】EventTrigger動態新增事件

【UGUI】EventTrigger動態新增事件

  EventTrigger trigger = type.gameObject.AddComponent<EventTrigger>();
        UnityAction<BaseEventData> action = new UnityAction<BaseEventData>(OnSelectDelegate);
        EventTrigger.Entry entry = new EventTrigger.Entry();
        entry.eventID = EventTriggerType.Select;
        entry.callback.AddListener(action);
        trigger.triggers.Add(entry);
    public void OnSelectDelegate(BaseEventData data)
    {
        Debug.Log("Onsubimt");
        
    }

這裡的type 是一個 Drop down物件

EventTrigger trigger = 你的物件.gameObject.AddComponent<EventTrigger>();
這是給這個Drop down 一個下拉框新增select事件





        
private void AddTriggersListener(GameObject obj, EventTriggerType eventID, UnityAction<BaseEventData> action)
    {
        EventTrigger trigger = obj.GetComponent<EventTrigger>();
        if (trigger == null)
        {
            trigger = obj.AddComponent<EventTrigger>();
        }

        if (trigger.triggers.Count == 0)
        {
            trigger.triggers = new List<EventTrigger.Entry>();
        }

        UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(action);
        EventTrigger.Entry entry = new EventTrigger.Entry();
        entry.eventID = eventID;
        entry.callback.AddListener(callback);
        trigger.triggers.Add(entry);
    }