-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGameStateListenerSM.cs
More file actions
100 lines (89 loc) · 3 KB
/
GameStateListenerSM.cs
File metadata and controls
100 lines (89 loc) · 3 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
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
namespace SO.SMachine
{
[System.Serializable]
public class gameStateListener
{
public GameStateSM GameState;
[Tooltip("must be enabled at first")]
public bool listenWhenDisabled;
public UnityEvent OnEnter;
//public UnityEvent OnPause;
//public UnityEvent OnUnPause;
public UnityEvent OnExit;
[TextArea]
[Tooltip("What does this object do in this GameState")]
public string GameStateBehaviour;
internal GameStateListenerSM source;
}
public class GameStateListenerSM : MonoBehaviour
{
//static Dictionary<int, GameStateListenerSM> inistances = null;
[SerializeField] private UnityEvent Init;
[SerializeField] private List<gameStateListener> StatesListeners = new List<gameStateListener>();
private bool isInitialized;
//GameStateListenerSM()
//{
// if (inistances == null) inistances = new Dictionary<int, GameStateListenerSM>();
//}
//private void Awake()
//{
// if (Application.isPlaying)
// inistances.Add(this.GetInstanceID(), this);
// else
// inistances = null;
//}
private void OnEnable()
{
Z.InvokeEndOfFrame(() =>
{
if (!isInitialized) { Init.Invoke(); isInitialized = true; }
for (int i = 0; i < StatesListeners.Count; i++)
{
StatesListeners[i].source = this;
StatesListeners[i].GameState.RegisterListener(StatesListeners[i]);
foreach (var stateListener in (GetComponentsInChildren<IStateListener>(true)))
{
if (this == ((MonoBehaviour)stateListener).gameObject.GetComponentInParent<GameStateListenerSM>())
StatesListeners[i].GameState.RegisterIListener(stateListener);
}
}
});
}
private void OnDestroy()
{
for (int i = 0; i < StatesListeners.Count; i++)
{
UnRigester(i);
}
}
private void OnDisable()
{
for (int i = 0; i < StatesListeners.Count; i++)
{
if (StatesListeners[i].listenWhenDisabled == false)
UnRigester(i);
}
}
private void UnRigester(int i)
{
try
{
StatesListeners[i].GameState.UnregisterListener(StatesListeners[i]);
StatesListeners[i].GameState.UnregisterIListeners(GetComponentsInChildren<IStateListener>());
}
catch (Exception)
{
}
}
}
public interface IStateListener
{
void OnEnter(GameStateSM gameState);
void OnExit(GameStateSM gameState);
}
}