您的位置:首页 > 移动开发 > Unity3D

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

2016-09-30 10:25 375 查看
实现类似下图的功能,金钱和能量的加减操作

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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: