SHADE_Y3/Assets/Scripts/Utility/UT_StateMachine.cs

127 lines
2.6 KiB
C#
Raw Permalink Normal View History

using SHADE;
using System;
using System.Collections.Generic;
using System.Linq;
2022-11-13 21:56:28 +08:00
public class StateMachine : Script
{
private Dictionary<Type, BaseState> stateDictionary;
public BaseState currentState = null;
public string currentStateName;
public string currentAnimName;
public void InitStateMachine(Dictionary<Type, BaseState> dictionary)
{
stateDictionary = dictionary;
currentState = stateDictionary.First().Value;
currentStateName = currentState.GetStateName();
currentAnimName = currentState.GetAnimName();
currentState.OnEnter();
}
public bool HasState(Type type)
{
if (!type.IsSubclassOf(typeof(BaseState)))
{
return false;
}
else
{
return stateDictionary.ContainsKey(type);
}
}
public void SetState(Type type)
{
if (!type.IsSubclassOf(typeof(BaseState)))
{
return;
}
if (stateDictionary.ContainsKey(type))
{
currentState.OnExit();
currentState = stateDictionary[type];
currentState.OnEnter();
}
else
{
SetState(stateDictionary.First().Key);
}
}
public BaseState GetState(Type type)
{
if (!stateDictionary.ContainsKey(type))
return null;
return stateDictionary[type];
}
2022-11-13 21:56:28 +08:00
public bool IsState(Type type)
{
return (currentState.GetType() == type);
}
2022-11-13 21:56:28 +08:00
protected override void update()
{
if (currentState != (null))
{
currentStateName = currentState.GetStateName();
currentAnimName = currentState.GetAnimName();
2022-11-13 21:56:28 +08:00
currentState.update();
}
}
2022-11-13 21:56:28 +08:00
protected override void fixedUpdate()
{
2022-11-13 21:56:28 +08:00
if (currentState != (null))
{
currentStateName = currentState.GetStateName();
currentAnimName = currentState.GetAnimName();
currentState.fixedUpdate();
}
}
2022-11-13 21:56:28 +08:00
protected override void onCollisionEnter(CollisionInfo info)
{
if (currentState != (null))
currentState.onCollisionEnter(info);
}
2022-11-13 21:56:28 +08:00
protected override void onCollisionStay(CollisionInfo info)
{
if (currentState != (null))
currentState.onCollisionStay(info);
}
2022-11-13 21:56:28 +08:00
protected override void onCollisionExit(CollisionInfo info)
{
if (currentState != (null))
currentState.onCollisionExit(info);
}
2022-11-13 21:56:28 +08:00
protected override void onTriggerEnter(CollisionInfo info)
{
if (currentState != (null))
currentState.onTriggerEnter(info);
}
2022-11-13 21:56:28 +08:00
protected override void onTriggerStay(CollisionInfo info)
{
if (currentState != (null))
currentState.onTriggerStay(info);
}
2022-11-13 21:56:28 +08:00
protected override void onTriggerExit(CollisionInfo info)
{
if (currentState != (null))
currentState.onTriggerExit(info);
}
}