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

\"\"

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

1).注册监听

2).移出监听

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

操作:

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

\"\"

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

\"\"

\"\"

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

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

\"\"

 

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

 \"\"

\"\"\"\"
 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.OnP GoldChange, OnP GoldValueChange);
15     }
16 
17     void OnP GoldValueChange(int gold)
18     {
19         goldText.text = gold.ToString();
20     }
21 
22     // Update is called once per  
23     void Update() {
24 
25     }
26     private void OnDestroy()
27     {
28         EventDispatcher.RemoveEventListener<int>(EventKey.OnP GoldChange, OnP GoldValueChange);
29 
30     }
31 
32     public void  ToAddGold()
33     {
34         P InfoManagerTest.Instance.P Gold += 100;
35     }
36 }
View Code

 

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

 \"\"

 

收藏 打印