Unity3D (C#)事件分發機制的實現

實現類似下圖的功能,金錢和能量的加減操作

using UnityEngine;
using System.Collections;

public class WindowCtr : MonoBehaviour {

    public CtrEnergy energyCtr;
    public CtrMoney moneyCtr;

    public Money money;
    public Energy energy;



    // Use this for initialization
    void Start () {
        //UIButton[] energyCtrArr = energyCtr.btnArr;
        //  UIButton[] moneyCtrArr = moneyCtr.btnArr;

        money = GetComponentInChildren<Money>();
        energy = GetComponentInChildren<Energy>();

        moneyCtr.clickCall += Click2;
        energyCtr.clickCall += Click1;


    }

    // Update is called once per frame
    //體力
    void Click1 (GameObject go) {
        Debug.Log("----體力-----");
        energy.SetEnergy(go.name);
    }

    //金錢
    void Click2(GameObject go)
    {
        Debug.Log("金錢");
        money.SetMoney(go.name);
    }
}
using UnityEngine;
using System.Collections;

public class CtrMoney : MonoBehaviour {

    public UIButton[] btnArr;

    //UIEventListener.VoidDelegate
    //聲明一個委託類型
    public delegate void VoidCall(GameObject go);
    //聲明一個事件
    public event VoidCall clickCall;

    // Use this for initialization
    void Awake () {
        btnArr = GetComponentsInChildren<UIButton>();

        for (int index = 0; index < btnArr.Length; index++)
        {
            UIEventListener.Get(btnArr[index].gameObject).onClick = Click;
        }

    }

    void Click(GameObject go)
    {
        if (clickCall == null) return;
        clickCall(go);//事件分發
    }

}
using UnityEngine;
using System.Collections;

public class CtrEnergy : MonoBehaviour {

    public UIButton[] btnArr;

    public event CtrMoney.VoidCall clickCall; 

   // public event UIEventListener.VoidDelegate clickEvent;
    // Use this for initialization
    void Awake()
    {
        btnArr = GetComponentsInChildren<UIButton>();
        for (int index = 0; index < btnArr.Length; index++)
        {
            UIEventListener.Get(btnArr[index].gameObject).onClick = Click;
        }
    }

    void Click(GameObject go)
    {
        if (clickCall != null)
            clickCall(go);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章