unity 事件订阅,发布,可用于新手引导

主要代码事件订阅,发布

##获取事件对象进行操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
using UnityEngine;
using System.Collections;
using System;
using System.Collections.Generic;

public class EventBase{
private List<Action> actions = new List<Action>();

/// <summary>
/// 发布事件
/// </summary>
public void Publish ()
{
if (actions != null) {
foreach (Action action in actions) {
action();
}
}
}

/// <summary>
/// 订阅事件
/// </summary>
/// <param name="t">T.</param>
public void Subscribe (Action t)
{
if (!actions.Contains (t)) {
actions.Add (t);
}
}

/// <summary>
/// 取消事件
/// </summary>
/// <param name="t">T.</param>
public void UnSubscribe (Action t)
{
if (actions.Contains (t)) {
actions.Remove (t);
}
}

public void Clear()
{
actions.Clear ();
}

}


public class EventBase<T>: EventBase{
private List<Action<T>> actions ;

public void Publish (T t)
{
if (actions != null) {
foreach (Action<T> action in actions) {
action(t);
}
}
}

public void Subscribe (Action<T> action)
{
if (actions == null) {
actions = new List<Action<T>>();
}
if (!actions.Contains (action)) {
actions.Add (action);
}
}

public void UnSubscribe (Action<T> action)
{
if (actions == null) {
return;
}
if (actions.Contains (action)) {
actions.Remove (action);
}
}

}



public class EventServer{
private static EventServer instance = new EventServer();

//存放事件对象集合
private Dictionary<Type,EventBase> evenbasci = new Dictionary<Type, EventBase>();

public static EventServer Instance {
get{
return instance;
}
}

/// <summary>
/// 获取事件对象,并对该对象进行订阅和发布
/// </summary>
/// <returns>The event.</returns>
/// <typeparam name="T">The 1st type parameter.</typeparam>
public T GetEvent<T> () where T: EventBase
{
Type eventtype = typeof(T);
if (!evenbasci.ContainsKey (eventtype)) {
//如果事件对象不存在,创建该事件对象
T e = Activator.CreateInstance <T>();
evenbasci.Add (eventtype,e);
}
return (T)evenbasci[eventtype];
}

public void ClearAll ()
{
foreach (EventBase e in evenbasci.Values) {
e.Clear ();
}

evenbasci.Clear ();
}
}

示例事件

1
2
3
4
5
using UnityEngine;
using System.Collections;

public class GuideTutor : EventBase {
}

用法

  • 在一定的地方订阅示例事件

    1
    2
    3
    4
    5
    6
    7
    8
    void Start () {
    EventServer.Instance.GetEvent<GuideTutor> ().Subscribe (EventLog);
    }

    void EventLog()
    {

    Debug.Log ("时间订阅");
    }
  • 在需要的地方发布事件

    1
    EventServer.Instance.GetEvent<GuideTutor> ().Publish ();