2024-04-11 01:55:35 -07:00
|
|
|
using System;
|
|
|
|
using System.Collections;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using System.Linq;
|
|
|
|
using System.Reflection;
|
|
|
|
using Sirenix.OdinInspector;
|
|
|
|
using UnityEngine;
|
|
|
|
|
|
|
|
namespace GadGame.State
|
|
|
|
{
|
|
|
|
public class StateRunner<T> : MonoBehaviour where T : MonoBehaviour
|
|
|
|
{
|
2024-04-15 04:10:00 -07:00
|
|
|
protected State<T> ActiveState;
|
2024-04-11 01:55:35 -07:00
|
|
|
|
|
|
|
#if UNITY_EDITOR
|
|
|
|
[ValueDropdown("AllStates")]
|
|
|
|
#endif
|
|
|
|
[SerializeField]
|
|
|
|
private List<string> _availableStates;
|
|
|
|
private List<State<T>> _states;
|
2024-04-15 04:10:00 -07:00
|
|
|
private float _timer;
|
2024-04-11 01:55:35 -07:00
|
|
|
|
|
|
|
#if UNITY_EDITOR
|
|
|
|
public IEnumerable AllStates
|
|
|
|
{
|
|
|
|
get
|
|
|
|
{
|
|
|
|
return Assembly.GetExecutingAssembly()
|
|
|
|
.GetTypes()
|
|
|
|
.Where(t => t.BaseType is { IsGenericType: true } &&
|
|
|
|
t.BaseType.GetGenericTypeDefinition() == typeof(State<>)).Select(t => t.FullName);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
#endif
|
|
|
|
|
|
|
|
|
|
|
|
protected virtual void Awake()
|
|
|
|
{
|
|
|
|
_states = new List<State<T>>();
|
|
|
|
|
|
|
|
foreach (var stateName in _availableStates)
|
|
|
|
{
|
|
|
|
var stateType = Assembly.GetExecutingAssembly().GetType(stateName);
|
|
|
|
var state = Activator.CreateInstance(stateType) as State<T>;
|
|
|
|
_states.Add(state);
|
|
|
|
state?.Init(GetComponent<T>());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-04-15 04:10:00 -07:00
|
|
|
protected virtual void Update()
|
2024-04-11 01:55:35 -07:00
|
|
|
{
|
2024-04-15 04:10:00 -07:00
|
|
|
if (ActiveState != null)
|
|
|
|
{
|
|
|
|
_timer += Time.deltaTime;
|
|
|
|
ActiveState.Update(_timer);
|
|
|
|
}
|
2024-04-11 01:55:35 -07:00
|
|
|
}
|
|
|
|
|
2024-04-15 04:10:00 -07:00
|
|
|
public void SetState<TSt>() where TSt : State<T>
|
2024-04-11 01:55:35 -07:00
|
|
|
{
|
2024-04-15 04:10:00 -07:00
|
|
|
if (ActiveState != null)
|
2024-04-11 01:55:35 -07:00
|
|
|
{
|
2024-04-15 04:10:00 -07:00
|
|
|
if(ActiveState is TSt) return;
|
|
|
|
ActiveState.Exit();
|
2024-04-11 01:55:35 -07:00
|
|
|
}
|
|
|
|
|
2024-04-15 04:10:00 -07:00
|
|
|
var newState = _states.FirstOrDefault(s => s is TSt);
|
2024-04-11 01:55:35 -07:00
|
|
|
if(newState == null) return;
|
2024-04-25 04:54:33 -07:00
|
|
|
newState.Enter();
|
2024-04-15 04:10:00 -07:00
|
|
|
ActiveState = newState;
|
|
|
|
_timer = 0;
|
2024-04-11 01:55:35 -07:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|