Search Unity

StateMachine Help

Discussion in 'Scripting' started by Zitant, Jun 10, 2019.

  1. Zitant

    Zitant

    Joined:
    May 26, 2019
    Posts:
    7
    Hello,

    Working a a state machine using interfaces. However, I'm having trouble getting the statemachine to change states when needed. Looking for a little guidance on possible structure that I may not be getting right now.

    First off I have the state machine script(Not MonoBehaviour):

    Code (CSharp):
    1. public class StateMachine
    2. {
    3.     public Dictionary<string, IState> gStates = new Dictionary<string, IState>();
    4.     public IState gCurrentState = new EmptyState();
    5.  
    6.  
    7.     public void Update(float elapsedTime)
    8.     {
    9.         gCurrentState.Update(elapsedTime);
    10.     }
    11.     public void Render()
    12.     {
    13.         gCurrentState.Render();
    14.     }
    15.     public void Change(string stateName)
    16.     {
    17.         gCurrentState.OnExit();
    18.         gCurrentState = gStates[stateName];
    19.         gCurrentState.OnEnter();
    20.     }
    21.     public void Add(string name, IState state)
    22.     {
    23.         gStates[name] = state;
    24.     }
    25.    
    26. }
    I have an interface setup for states to use which looks like this:
    Code (CSharp):
    1. public interface IState
    2. {
    3.     void Update(float elapsedTime);
    4.     void Render();
    5.     void OnEnter();
    6.     void OnExit();
    7. }
    and i'm creating/starting the state machine in my Game Manager:
    Code (CSharp):
    1. public StateMachine gGameMode = new StateMachine();
    2.  
    3. //skipping unrelated code
    4.  
    5. public void Update()
    6.     {
    7.         float elapsedTime = Time.deltaTime;
    8.         gGameMode.Update(elapsedTime);
    9.         gGameMode.Render();
    10.         Debug.Log(gGameMode.gCurrentState);
    11.     }
    12.  
    13.     public void MainStateMachine()
    14.     {
    15.         gGameMode.Add("mainmenu", new MainMenuState());
    16.         gGameMode.Add("battle", new BattleState());
    17.         gGameMode.Add("emptystate", new EmptyState());
    18.  
    19.         gGameMode.Change("mainmenu");
    20.     }
    So the game manager creates the Game machine. However, I'm having trouble getting other scripts to interact and change the state when needed. I was trying to avoid using MonoBehaviour but I think that's the missing link. Separate scripts are made for each state but they are not inheriting from MonoBehaviour. Only trying to work with two right now.

    I've been playing around with it and I can get it to work but it's not exactly how I envision it. I feel like I'm missing something conceptional about how to interact with the statemachine.
     
  2. Zitant

    Zitant

    Joined:
    May 26, 2019
    Posts:
    7
    disregard - I found documentation for what I'm trying to do.