-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathEventBus.cs
More file actions
129 lines (108 loc) · 3.45 KB
/
EventBus.cs
File metadata and controls
129 lines (108 loc) · 3.45 KB
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
124
125
126
127
128
129
using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityEventBus
{
/// <summary>
/// Event bus, with auto subscription functionality
/// </summary>
public class EventBus : EventBusBase, ISubscriberOptions
{
public string Name => name;
public int Priority
{
get => m_Priority;
set
{
if (m_Priority == value)
return;
m_Priority = value;
// reconnect if order was changed
if (m_Connected)
{
_disconnectBus();
_connectBus();
}
}
}
[SerializeField]
private SubscriptionTarget m_SubscribeTo = SubscriptionTarget.Global;
[SerializeField]
private int m_Priority;
private bool m_Connected;
private List<IEventBus> m_Subscriptions = new List<IEventBus>();
// =======================================================================
[Serializable] [Flags]
public enum SubscriptionTarget
{
None = 0,
/// <summary> EventBus singleton </summary>
Global = 1,
/// <summary> First parent EventBus </summary>
FirstParent = 1 << 1,
}
public SubscriptionTarget SubscribeTo
{
get => m_SubscribeTo;
set
{
if (m_SubscribeTo == value)
return;
m_SubscribeTo = value;
if (m_Connected)
{
_disconnectBus();
_buildSubscriptionList();
_connectBus();
}
else
_buildSubscriptionList();
}
}
// =======================================================================
protected override void Awake()
{
base.Awake();
_buildSubscriptionList();
}
protected virtual void OnEnable()
{
_connectBus();
}
protected virtual void OnDisable()
{
_disconnectBus();
}
// =======================================================================
private void _disconnectBus()
{
if (m_Connected == false)
return;
m_Connected = false;
foreach (var bus in m_Subscriptions)
bus.UnSubscribe(this);
}
private void _connectBus()
{
if (m_Connected)
return;
m_Connected = true;
foreach (var bus in m_Subscriptions)
bus.Subscribe(this);
}
private void _buildSubscriptionList()
{
m_Subscriptions.Clear();
if (m_SubscribeTo == SubscriptionTarget.None)
return;
if (m_SubscribeTo.HasFlag(SubscriptionTarget.Global) && GlobalBus.Instance != null)
m_Subscriptions.Add(GlobalBus.Instance);
if (m_SubscribeTo.HasFlag(SubscriptionTarget.FirstParent) && transform.parent != null)
{
var firstParent = transform.parent.GetComponentInParent<IEventBus>();
if (firstParent != null)
m_Subscriptions.Add(firstParent);
}
}
}
}