SanAndreasUnity/Assets/Scripts/Utilities/StateContainer.cs

69 lines
1.8 KiB
C#
Raw Normal View History

2021-09-19 22:44:31 +00:00
using System;
using System.Collections.Generic;
2021-09-19 21:29:51 +00:00
using System.Linq;
using UnityEngine;
namespace SanAndreasUnity.Utilities
{
/// <summary>
/// Container for <see cref="IState"/> objects.
/// </summary>
public class StateContainer<TState>
where TState : IState
{
private readonly List<TState> _states = new List<TState>();
public IReadOnlyList<TState> States => _states;
public TState GetState(System.Type type)
{
return this._states.FirstOrDefault (s => s.GetType ().Equals (type));
}
public T GetState<T>()
where T : TState
{
return (T) this.GetState(typeof(T));
}
public TState GetStateOrLogError(System.Type type)
{
var state = this.GetState (type);
if(null == state)
2021-09-19 22:44:31 +00:00
Debug.LogErrorFormat ("Failed to find state of type {0}", type);
2021-09-19 21:29:51 +00:00
return state;
}
public T GetStateOrLogError<T>()
where T : TState
{
return (T) this.GetStateOrLogError(typeof(T));
}
2021-09-19 22:44:31 +00:00
public T GetStateOrThrow<T>()
where T : TState
{
var state = this.GetState<T>();
if (null == state)
throw new ArgumentException($"Failed to find state of type {typeof(T).Name}");
return state;
}
2021-12-18 14:55:04 +00:00
public IEnumerable<TState> GetStatesThatInherit<TParent>()
where TParent : IState
{
return _states.OfType<TParent>().Cast<TState>();
}
2021-09-19 21:29:51 +00:00
public void AddState(TState stateToAdd)
{
_states.Add(stateToAdd);
}
public void AddStates(IEnumerable<TState> statesToAdd)
{
_states.AddRange(statesToAdd);
}
}
}