UI Stack (C# / Unity)
A C# implementation of a UI stack for managing UI panels and their transitions, originally written as part of a personal library for Unity games called Gemini.
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.Generic; using UnityEngine.Assertions; namespace Gemini { public class UIStack { #region public [Flags] public enum Transition { None = 0, Intro = 1, Outro = 2, Full = Intro | Outro } public UIStack() { m_stack = new Stack } public int Count { get { return m_stack.Count; } } public void Push( IUIPanel panel ) { Push( panel, Transition.Full ); } public void Push( IUIPanel panel, Transition transition ) { Assert.IsNotNull( panel, "UIStack.Push: panel is null" ); // hide top if ( Count > 0 ) { IUIPanel curPanel = Peek(); curPanel.Active = false; curPanel.OnHide( BitField.IsFlagSet( transition, Transition.Outro ) ); } // push new m_stack.Push( panel ); panel.Active = true; panel.OnPush( BitField.IsFlagSet( transition, Transition.Intro ) ); } public IUIPanel Pop() { return Pop( Transition.Full ); } public IUIPanel Pop( Transition transition ) { // pop top IUIPanel poppedPanel = m_stack.Pop(); Assert.IsNotNull( poppedPanel, "UIStack.Pop: Top panel is null" ); poppedPanel.Active = false; poppedPanel.OnPop( BitField.IsFlagSet( transition, Transition.Outro ) ); // show prev if ( Count > 0 ) { IUIPanel newTop = Peek(); Assert.IsNotNull( poppedPanel, "UIStack.Pop: New top panel is null" ); newTop.Active = true; newTop.OnShow( BitField.IsFlagSet( transition, Transition.Intro ) ); } return poppedPanel; } public void Clear() { m_stack.Clear(); } public IUIPanel Peek() { Assert.IsTrue( Count > 0, "UIStack.Peek: The stack is empty" ); return m_stack.Peek(); } public bool Contains( IUIPanel panel ) { return m_stack.Contains( panel ); } #endregion // public #region private private Stack #endregion // private } } |