事件系统,首先把插件拖进当前项目中
然后在EventKey中添加监听事件
简易UI测试
需要一个玩家信息类,然后做成单例模式
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerInfoManagerTest {
#region 单例模式
private static PlayerInfoManagerTest instance;
public static PlayerInfoManagerTest Instance
{
get
{
if (instance == null)
{
instance = new PlayerInfoManagerTest();
}
return instance;
}
}
private PlayerInfoManagerTest() { }//初始化类
#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;
// Use this for initialization
void Start()
{
//启动添加监听(监听事件名字,需要调用的方法)
EventDispatcher.AddEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange);
}
void OnPlayerGoldValueChange(int gold)
{
goldText.text = gold.ToString();
}
// Update is called once per frame
void Update() {
}
private void OnDestroy()
{
//移除监听
EventDispatcher.RemoveEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange);
}
public void OnClickToAddGold()
{
//按钮监听事件
PlayerInfoManagerTest.Instance.PlayerGold += 100;
}
}
另外,事件可由多个物体监听,只需在游戏物体上挂载监听脚本即可
例如示例中的Cube,当金币改变时会改变自己的激活状态,脚本如下
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CubeHide : MonoBehaviour {
// Use this for initialization
void Start () {
//添加监听
EventDispatcher.AddEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange);
}
private void OnPlayerGoldValueChange(int gold)//若监听事件触发,需要做的事情
{
gameObject.SetActive(!gameObject.activeSelf);
}
// Update is called once per frame
void Update () {
}
private void OnDestroy()
{
//移除监听
EventDispatcher.RemoveEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange);
}
}