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();
        energy = GetComponentInChildren();

        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();

        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();
        for (int index = 0; index < btnArr.Length; index++)
        {
            UIEventListener.Get(btnArr[index].gameObject).onClick = Click;
        }
    }

    void Click(GameObject go)
    {
        if (clickCall != null)
            clickCall(go);
    }
}

你可能感兴趣的:(C#,Unity3D)