I am creating a Finite State Machine for use in Unity for an enemy in a game.
All the states are made from an EmptyState.cs blueprint that defines the state exit, update, and start functions, and all states are derived from it.
In my FSM core, I have a dictionary reference to all states, and the current state;
private Dictionary<Type, EmptyState> amalgamStates;
public EmptyState currentState;
The dictionary, looks like this;
Dictionary<Type, EmptyState> states = new Dictionary<Type, EmptyState>
{
{typeof(RoamingState), new RoamingState() },
{typeof(IdleState), new IdleState() },
{typeof(StalkingState), new StalkingState() },
{typeof(HuntingState), new HuntingState() },
{typeof(HauntingState), new HauntingState() },
{typeof(LeavingState), new LeavingState() }
};
However, when I assign a state to currentState, it always sets as null.
private void Update()
{
if (currentState == null)
{
currentState = amalgamStates.Values.First(); **<--- here**
Debug.Log(currentState);
currentState.stateStart(amalgamBrain);
}
//Run state's update and store output (output will be next state)
var temp = currentState.stateUpdate(amalgamBrain);
//If the stored state is different -> switch states to new state
if (temp != currentState.GetType())
{
switchStates(temp);
}
}
Debug.Log(currentState);
always returns null. I can’t even set the variable manually in the unity inspector.
I know that this should work, as I am working from a project of a similar framework that works fine, so I’m just making a dumb mistake somewhere. Does anyone have any ideas? Here is the entirety of EmptyState.cs to anyone curious.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EmptyState : MonoBehaviour
{
public AmalgamCentralAI amalgamBrain;
public virtual void stateStart(AmalgamCentralAI amalgamBrain) { }
public virtual Type stateUpdate(AmalgamCentralAI amalgamBrain) { return null; }
public virtual void stateExit(AmalgamCentralAI amalgamBrain) { }
}
``
2