Last active
January 1, 2019 18:42
-
-
Save arvidsson/5ff7dffcf0d996050332ee32d0dd9417 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Collections.Generic; | |
using UnityEngine; | |
public class FSMState : MonoBehaviour | |
{ | |
private void Awake() | |
{ | |
Setup(); | |
} | |
private void OnDestroy() | |
{ | |
Teardown(); | |
} | |
private void OnEnable() | |
{ | |
GainControl(); | |
} | |
private void OnDisable() | |
{ | |
LoseControl(); | |
} | |
protected virtual void Setup() { } | |
protected virtual void Teardown() { } | |
protected virtual void GainControl() { } | |
protected virtual void LoseControl() { } | |
} | |
public class TestState : FSMState | |
{ | |
protected override void Setup() | |
{ | |
Debug.Log("Initialize state"); | |
} | |
protected override void Teardown() | |
{ | |
Debug.Log("Destroy state"); | |
} | |
protected override void GainControl() | |
{ | |
Debug.Log("State gained control"); | |
} | |
protected override void LoseControl() | |
{ | |
Debug.Log("State lost control"); | |
} | |
} | |
public class FSM : MonoBehaviour | |
{ | |
private static FSM instance; | |
private Stack<FSMState> states = new Stack<FSMState>(); | |
private bool IsEmpty { get { return states.Count == 0; } } | |
private void Awake() | |
{ | |
instance = this; | |
} | |
public static void Push<T>() where T : FSMState | |
{ | |
instance.PushState<T>(); | |
} | |
public static void Pop() | |
{ | |
instance.PopState(); | |
} | |
private void PushState<T>() where T : FSMState | |
{ | |
Debug.Assert(states != null); | |
if (!IsEmpty) | |
{ | |
var prev = states.Peek(); | |
prev.enabled = false; | |
} | |
var cur = gameObject.AddComponent<T>(); | |
states.Push(cur); | |
} | |
private void PopState() | |
{ | |
Debug.Assert(states != null); | |
if (!IsEmpty) | |
{ | |
var cur = states.Pop(); | |
Destroy(cur); | |
if (!IsEmpty) | |
{ | |
var prev = states.Peek(); | |
prev.enabled = true; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment