Created
March 17, 2022 22:49
-
-
Save phosphoer/96b254e3a8a017a86918cc416819d40e to your computer and use it in GitHub Desktop.
A 'reference counted' bool state so it can be written to from multiple places without clobbering state.
This file contains hidden or 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 UnityEngine; | |
public class BoolStateStack | |
{ | |
public event System.Action StatePushed; | |
public event System.Action StatePopped; | |
public bool IsActive => _count > 0; | |
private int _count; | |
private bool _warnBelowZero; | |
private string _name; | |
public BoolStateStack() | |
{ | |
_count = 0; | |
_warnBelowZero = true; | |
_name = "unnamed"; | |
} | |
public BoolStateStack(bool warnBelowZero, string name) | |
{ | |
_count = 0; | |
_warnBelowZero = warnBelowZero; | |
_name = name; | |
} | |
public static implicit operator bool(BoolStateStack rhs) | |
{ | |
return rhs.IsActive; | |
} | |
public void Set(bool active) | |
{ | |
_count = active ? 1 : 0; | |
} | |
public void Push() | |
{ | |
_count += 1; | |
StatePushed?.Invoke(); | |
} | |
public void Pop() | |
{ | |
_count -= 1; | |
if (_count < 0) | |
{ | |
_count = 0; | |
Debug.LogWarning($"BoolStateStack {_name} went below 0 to {_count}"); | |
} | |
StatePopped?.Invoke(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment