事件系统用途普遍,对处理玩家数据有很大帮助(玩家金币,经验,等级),让数据屡次调用,下降耦合ide
在unity中应用(以玩家金币发生变化来演示);this
1).注册监听spa
2).移出监听3d
3).金币发生变化的时候,通知每一个界面code
操做:blog
1.将Event三个脚本导入工程中;事件
2.写一个脚本,PlayerInforManagerTest,脚本主要做用是存储用户数据,其余脚本须要数据时就在这个脚本中调用,利用事件系统get
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 5 public class PlayerInfoManagerTest { 6 7 #region 单例模式 8 private static PlayerInfoManagerTest instance; 9 10 public static PlayerInfoManagerTest Instance 11 { 12 get 13 { 14 if (instance == null) 15 { 16 instance = new PlayerInfoManagerTest(); 17 } 18 return instance; 19 } 20 } 21 22 private PlayerInfoManagerTest() { } 23 #endregion 24 25 26 private int playerGold; 27 28 public int PlayerGold { 29 30 get { return playerGold; } 31 32 set { 33 //以前玩家金币数值 != 设置过来的数值 34 if (playerGold != value) 35 { 36 playerGold = value; 37 //数值发生变化 通知注册当前 金币发生变化的 界面 38 EventDispatcher.TriggerEvent<int>(EventKey.OnPlayerGoldChange, playerGold); 39 40 } 41 42 43 44 } 45 } 46 47 48 49 }
3).在事件系统的EventKey脚本中添加须要改变数据的Keyit
4).写一个脚本EventTest,做用是做为改变数据而调用事件系统,至关于一个商店购买(出售)装备时,金币减小(增长),通知玩家PlayerInforManagerTest数据中心更新数据,从而让其余(如玩家背包显示金币)脚本调用PlayerInforManagerTest时数据一致.io
1 using System.Collections; 2 using System.Collections.Generic; 3 using UnityEngine; 4 using UnityEngine.UI; 5 6 7 public class EventTest : MonoBehaviour { 8 9 public Text goldText; 10 11 // Use this for initialization 12 void Start() 13 { 14 EventDispatcher.AddEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange); 15 } 16 17 void OnPlayerGoldValueChange(int gold) 18 { 19 goldText.text = gold.ToString(); 20 } 21 22 // Update is called once per frame 23 void Update() { 24 25 } 26 private void OnDestroy() 27 { 28 EventDispatcher.RemoveEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange); 29 30 } 31 32 public void OnClickToAddGold() 33 { 34 PlayerInfoManagerTest.Instance.PlayerGold += 100; 35 } 36 }
5).在unity中添加button和金币Text文本,挂载脚本实现.