事件监听的原理:比如改变玩家金币是一个事件,数据中心接受到要改变玩家金币的信息,金币发生变化的时候,通知每个注册过这个事件的界面(也就是这个事件的订阅者),要进行什么操作.
举个例子:我现在要点击一下按钮就让金币数加100
首先,我应该先顶一下金币发生改变
其次,
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInfoManagerTest {
#region 单例模式
private static PlayerInfoManagerTest instance;
private PlayerInfoManagerTest()
{
}
public static PlayerInfoManagerTest Instance
{
get
{
if (instance == null)
{
instance = new PlayerInfoManagerTest();
}
return instance;
}
}
#endregion
private int playerGold;
public int PlayerGold
{
get { return playerGold; }
set
{
//玩家之前的金币数值 != 设置过来的竖直
if (playerGold != value)
{
playerGold = value;
//金币数值发生变化后 通知所有注册当前金币发生变化的界面(向外抛事件)
EventDispatcher.TriggerEvent<int>(EventKey.OnPlayerGoldChange, playerGold);
}
}
}
}
最后,注册监听事件和移除监听事件 和按钮的点击事件
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class EventTest : MonoBehaviour {
public Text goldtext;
private Button AddGoldBtn;
void Start () {
AddGoldBtn = transform.Find("Button").GetComponent<Button>();
AddGoldBtn.onClick.AddListener(OnClickToAddGold);
//注册监听事件
EventDispatcher.AddEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange);
}
void OnPlayerGoldValueChange(int gold)
{
goldtext.text = gold.ToString();
}
void Update () {
}
private void OnDestroy()
{
//移除监听事件
EventDispatcher.RemoveEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange);
}
private void OnClickToAddGold()
{
//点击按钮让 金币 +100
PlayerInfoManagerTest.Instance.PlayerGold += 100;
}
}
每点击一次金币数就会往上加100