Skip to content

Instantly share code, notes, and snippets.

@phosphoer
Created March 17, 2022 22:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phosphoer/96b254e3a8a017a86918cc416819d40e to your computer and use it in GitHub Desktop.
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.
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