这一篇来看看怎么用这个EventCenter
首先是一个测试脚本,把它挂到一个空对象上面去即可:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TestEventScript : MonoBehaviour
{
// Use this for initialization
void Start ()
{
//这里先添加监听
EventCenter.AddListener (EGameEvent.eGameEvent_UpLv, Test);
}
// Update is called once per frame
void Update ()
{
}
void OnDestroy()
{
//有添加就肯定有销毁
EventCenter.RemoveListener (EGameEvent.eGameEvent_UpLv, Test);
}
public void Test ()
{
Debug.Log ("没有参数的监听!!!");
}
}
然后再场景中创建一个button(button总会用吧),绑定它的点击事件:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ButtonClick : MonoBehaviour {
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void ClickButton()
{
//事件分发
EventCenter.Broadcast (EGameEvent.eGameEvent_UpLv);
}
}
运行结果:
接下来是传递一个参数的用法:
//这里先添加监听
EventCenter.AddListener<string> (EGameEvent.eGameEvent_UpLv, Test<string>);
//有添加就肯定有销毁
EventCenter.RemoveListener<string> (EGameEvent.eGameEvent_UpLv, Test<string>);
public void Test<T> (T str1)
{
Debug.Log ("str1: " + str1);
}
public void ClickButton()
{
//事件分发
EventCenter.Broadcast<string> (EGameEvent.eGameEvent_UpLv, str1);
}
运行结果:
接下来是传递两个参数的方法:
//这里先添加监听
EventCenter.AddListener<string, int> (EGameEvent.eGameEvent_UpLv, Test<string, int>);
//有添加就肯定有销毁
EventCenter.RemoveListener<string, int> (EGameEvent.eGameEvent_UpLv, Test<string, int>);
public void Test<T, U> (T str1, U integer2)
{
Debug.Log ("str1: " + str1 + " " + "integer2:" + integer2.ToString());
}
public void ClickButton()
{
//事件分发
EventCenter.Broadcast<string, int> (EGameEvent.eGameEvent_UpLv, str1, integer2);
}
运行结果:
接下来三个参数,四个参数应该也没问题了。