using System; using System.Collections.Generic; using System.Linq; using UnityEngine; namespace SanAndreasUnity.Utilities { /// /// Container for objects. /// public class StateContainer where TState : IState { private readonly List _states = new List(); public IReadOnlyList States => _states; public TState GetState(System.Type type) { return this._states.FirstOrDefault (s => s.GetType ().Equals (type)); } public T GetState() where T : TState { return (T) this.GetState(typeof(T)); } public TState GetStateOrLogError(System.Type type) { var state = this.GetState (type); if(null == state) Debug.LogErrorFormat ("Failed to find state of type {0}", type); return state; } public T GetStateOrLogError() where T : TState { return (T) this.GetStateOrLogError(typeof(T)); } public T GetStateOrThrow() where T : TState { var state = this.GetState(); if (null == state) throw new ArgumentException($"Failed to find state of type {typeof(T).Name}"); return state; } public IEnumerable GetStatesThatInherit() where TParent : IState { return _states.OfType().Cast(); } public void AddState(TState stateToAdd) { _states.Add(stateToAdd); } public void AddStates(IEnumerable statesToAdd) { _states.AddRange(statesToAdd); } } }