方法一:
Unity (64bit) - A.unity - New Unity Project - PC, Mac & Linux Standalone DX11_2  
// 請把此程式掛在 Canvas 上,然後拖一張 Sprite 圖片進來

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;
using System.Collections;

public class Test : MonoBehaviour {

    public Sprite img;

    void Start () {
        GameObject g = new GameObject ("My Button", typeof(RectTransform), typeof(Image), typeof(Button));

        Transform t = g.transform;
        t.SetParent (transform);
        t.localPosition = Vector3.zero;

        Image img2 = g.GetComponent<Image> ();
        img2.sprite = img;;
        img2.SetNativeSize ();

        Button.ButtonClickedEvent e = new Button.ButtonClickedEvent();
        e.AddListener(Kiss);

        Button b = g.GetComponent<Button> ();
        b.onClick = e;

    }

    public void Kiss(){
        print ("Kiss");
    }

}



方法二:

// 把此程式拖到該按鈕上,就可以觸發函式,好處是可以動態加入 EventTrigger 

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

public class MyButton2 : MonoBehaviour {

    void Awake (){

        EventTrigger.Entry entry = new EventTrigger.Entry();// 定義需要绑定的事件類型。並設定回調函式
        entry.eventID = EventTriggerType.PointerClick;// 設定事件類型
        entry.callback = new EventTrigger.TriggerEvent();// 設定回調函式
        UnityAction<BaseEventData> callback = new UnityAction<BaseEventData>(Hello);
        entry.callback.AddListener(callback);

        EventTrigger trigger = transform.gameObject.AddComponent<EventTrigger>();
        trigger.delegates = new List<EventTrigger.Entry>();// 實體化 delegates
        trigger.delegates.Add(entry);// 添加事件觸發,記錄到 GameObject 的事件觸發元件
    }

    public void Hello(BaseEventData data){
        print("Hello");
    }

}


方法三:

// 把此程式拖到該按鈕上,就可以觸發函式,像是 NGUI 的 OnClick() 的使用方式 (例外:這不是自動產生呦~)

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using UnityEngine.Events;
using UnityEngine.EventSystems;

public class MyButton1 : MonoBehaviour, IPointerClickHandler {

    public void OnPointerClick(PointerEventData eventData) {
        print ("My Button 1");
    }

}







創作者介紹
創作者 黃彥霖 的頭像
黃彥霖

彥霖 實驗筆記

黃彥霖 發表在 痞客邦 留言(0) 人氣()