Unity3D (C#)事件分发机制的实现

11 篇文章 0 订阅

实现类似下图的功能,金钱和能量的加减操作

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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值