state machine - get current state through code

Ed WonWon 3 years ago updated 3 years ago 2

We need a way to get the current high level state of a state machine, is this possible?

For example, a string that says whether this state machine is in Content, Bored, Hunger, or Tired that I can access via the State Machine component. 

Bolt Version:
Unity Version:
Scripting Backend:
.NET Version (API Compatibility Level):

Yes, but it's not as simple as you may think :)

Here's a one-liner for it:

var title = GetComponent<StateMachine>().nest.graph.states.OfType<IGraphNesterState>().First(s => s.isActive).nest.graph.title;

This only returns the title of the first active state. For example, in your graph, it might return "Tick Stats".

If you want an array with all active titles, you could do:

var titles = GetComponent<StateMachine>().nest.graph.states.OfType<IGraphNesterState>().Where(s => s.isActive).Select(s => s.nest.graph.title).ToArray();

excellent, thank you!