-
Notifications
You must be signed in to change notification settings - Fork 0
/
Pattern_Decoupling Gameplay via the Observer Pattern.cs
99 lines (83 loc) · 2.55 KB
/
Pattern_Decoupling Gameplay via the Observer Pattern.cs
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
// The observer pattern is a design pattern that is used to define a one-to-many dependency between objects, such that when one object changes state, all of its dependents are notified and updated automatically. It allows objects to communicate and stay in sync with each other without tight coupling.
public class WaveData : MonoBehaviour
{
private List<IObserver> observers = new List<IObserver>();
private int waveNumber;
private int lives;
public void AddObserver(IObserver observer)
{
observers.Add(observer);
}
public void RemoveObserver(IObserver observer)
{
observers.Remove(observer);
}
public void NotifyObservers()
{
foreach (IObserver observer in observers)
{
observer.OnNotify();
}
}
public int WaveNumber
{
get { return waveNumber; }
set
{
waveNumber = value;
NotifyObservers();
}
}
public int Lives
{
get { return lives; }
set
{
lives = value;
NotifyObservers();
}
}
}
public interface IObserver
{
void OnNotify();
}
public class WaveNumberText : IObserver
{
private WaveData waveData;
private Text text;
public WaveNumberText(WaveData waveData, Text text)
{
this.waveData = waveData;
this.text = text;
}
public void OnNotify()
{
text.text = "Wave: " + waveData.WaveNumber;
}
}
public class LivesText : IObserver
{
private WaveData waveData;
private Text text;
public LivesText(WaveData waveData, Text text)
{
this.waveData = waveData;
this.text = text;
}
public void OnNotify()
{
text.text = "Lives: " + waveData.Lives;
}
}
// To use this system in your game, you can create instances of the WaveData class and the UI element classes and register the UI element instances as observers of the WaveData instance. For example:
WaveData waveData = new WaveData();
Text waveNumberText = GameObject.Find("WaveNumberText").GetComponent<Text>();
IObserver waveNumberObserver = new WaveNumberText(waveData, waveNumberText);
waveData.AddObserver(waveNumberObserver);
Text livesText = GameObject.Find("LivesText").GetComponent<Text>();
IObserver livesObserver = new LivesText(waveData, livesText);
waveData.AddObserver(livesObserver);
// whenever you update the wave number or remaining lives in the WaveData instance, the UI elements will be automatically updated to reflect the new values.
waveData.WaveNumber = 5;
waveData.Lives = 3;