Improving FSMs: hierarchical finite-state machines

Finite-state machines can be improved in terms of having different layers or hierarchies. The principles are the same, but states are able to have their own internal finite-state machine, making them more flexible and scalable.

Getting ready

This recipe is based on top of the previous recipe, so it is important that we grasp and understand how the finite-state machine recipe works.

How to do it...

We will create a state that is capable of holding internal states, in order to develop multi-level hierarchical state machines:

  1. Create the StateHighLevel class deriving from State:
    using UnityEngine;
    using System.Collections;
    using System.Collections.Generic;
    
    public class StateHighLevel : State
    {
    }
  2. Add the new member variables to control the internal states:
    public List<State> states;
    public State stateInitial;
    protected State stateCurrent;
  3. Override the initialization function:
    public override void OnEnable()
    {
        if (stateCurrent == null)
            stateCurrent = stateInitial;
        stateCurrent.enabled = true;
    }
  4. Override the finalization function:
    public override void OnDisable()
    {
        base.OnDisable();
        stateCurrent.enabled = false;
        foreach (State s in states)
        {
            s.enabled = false;
        }
    }

How it works...

The high-level state class lets us activate the internal FSMs when it is enabled and recursively disables its internal states when disabled. The working principle stays the same thanks to the list of states and the way the parent class resolves the transitioning process.

See also

Kindly refer to the recipe, Working a finite-state machine.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.15.135.175