VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > 编程开发 > c#教程 >
  • C#教程之C#教程之GameFreamWork框架----事件系统的应用

本站最新发布   C#从入门到精通
试听地址  
https://www.xin3721.com/eschool/CSharpxin3721/

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

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

1).注册监听

2).移出监听

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

操作:

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

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

复制代码
 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脚本中添加需要改变数据的Key

 

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

 

复制代码
 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文本,挂载脚本实现.

 

 

相关教程