1. 程式人生 > >Unity 利用 UnityAction 對多個按鈕新增監聽

Unity 利用 UnityAction 對多個按鈕新增監聽

當有許多個按鈕需要新增監聽的時候,我們可以先使用UnityAction把這些方法監聽起來,再分別傳給按鈕。



public UnityEngine.Events.UnityAction[] allEvents = new UnityEngine.Events.UnityAction[3];



void Start () {
    //一些初始化
    mAS = this.GetComponent<AudioSource> ();

    mVideoPlayer = this.GetComponent<VideoPlayer> ();

    mVideoPlayer.clip = mVClips [num];

    timeCtrl.onValueChanged.AddListener (ChangeTime);

 
    //監聽方法
    allEvents [0] = () => {

        chooseVideo = -1;

    };
    //監聽方法
    allEvents [1] = () => {

        videoIsPlaying = !videoIsPlaying;

    };
    //監聽方法
    allEvents [2] = () => {

        chooseVideo = 1;

    };



    for (int i = 0; i < btns.Length; i++) {
        //給按鈕等新增監聽
        btns [i].onClick.AddListener (allEvents [i]);

    }

}