经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 程序设计 » C# » 查看文章
GameFreamWork框架----事件系统的应用
来源:cnblogs  作者:薄荷グ微凉べ  时间:2018/12/17 9:51:53  对本文有异议

事件系统用途广泛,对处理玩家数据有很大帮助(玩家金币,经验,等级),让数据多次调用,降低耦合

在unity中应用(以玩家金币发生变化来演示);

1).注册监听

2).移出监听

3).金币发生变化的时候,通知每个界面

操作:

1.将Event三个脚本导入工程中;

2.写一个脚本,PlayerInforManagerTest,脚本主要作用是存储用户数据,其他脚本需要数据时就在这个脚本中调用,利用事件系统

  1. 1 using System.Collections;
  2. 2 using System.Collections.Generic;
  3. 3 using UnityEngine;
  4. 4
  5. 5 public class PlayerInfoManagerTest {
  6. 6
  7. 7 #region 单例模式
  8. 8 private static PlayerInfoManagerTest instance;
  9. 9
  10. 10 public static PlayerInfoManagerTest Instance
  11. 11 {
  12. 12 get
  13. 13 {
  14. 14 if (instance == null)
  15. 15 {
  16. 16 instance = new PlayerInfoManagerTest();
  17. 17 }
  18. 18 return instance;
  19. 19 }
  20. 20 }
  21. 21
  22. 22 private PlayerInfoManagerTest() { }
  23. 23 #endregion
  24. 24
  25. 25
  26. 26 private int playerGold;
  27. 27
  28. 28 public int PlayerGold {
  29. 29
  30. 30 get { return playerGold; }
  31. 31
  32. 32 set {
  33. 33 //之前玩家金币数值 != 设置过来的数值
  34. 34 if (playerGold != value)
  35. 35 {
  36. 36 playerGold = value;
  37. 37 //数值发生变化 通知注册当前 金币发生变化的 界面
  38. 38 EventDispatcher.TriggerEvent<int>(EventKey.OnPlayerGoldChange, playerGold);
  39. 39
  40. 40 }
  41. 41
  42. 42
  43. 43
  44. 44 }
  45. 45 }
  46. 46
  47. 47
  48. 48
  49. 49 }
View Code

 3).在事件系统的EventKey脚本中添加需要改变数据的Key

 

4).写一个脚本EventTest,作用是作为改变数据而调用事件系统,相当于一个商店购买(出售)装备时,金币减少(增加),通知玩家PlayerInforManagerTest数据中心更新数据,从而让其他(如玩家背包显示金币)脚本调用PlayerInforManagerTest时数据一致.

 

  1. 1 using System.Collections;
  2. 2 using System.Collections.Generic;
  3. 3 using UnityEngine;
  4. 4 using UnityEngine.UI;
  5. 5
  6. 6
  7. 7 public class EventTest : MonoBehaviour {
  8. 8
  9. 9 public Text goldText;
  10. 10
  11. 11 // Use this for initialization
  12. 12 void Start()
  13. 13 {
  14. 14 EventDispatcher.AddEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange);
  15. 15 }
  16. 16
  17. 17 void OnPlayerGoldValueChange(int gold)
  18. 18 {
  19. 19 goldText.text = gold.ToString();
  20. 20 }
  21. 21
  22. 22 // Update is called once per frame
  23. 23 void Update() {
  24. 24
  25. 25 }
  26. 26 private void OnDestroy()
  27. 27 {
  28. 28 EventDispatcher.RemoveEventListener<int>(EventKey.OnPlayerGoldChange, OnPlayerGoldValueChange);
  29. 29
  30. 30 }
  31. 31
  32. 32 public void OnClickToAddGold()
  33. 33 {
  34. 34 PlayerInfoManagerTest.Instance.PlayerGold += 100;
  35. 35 }
  36. 36 }
View Code

 

5).在unity中添加button和金币Text文本,挂载脚本实现.

 

 

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号