state machine - get current state through code

Ed WonWon 4 years ago updated by Breno Azevedo 1 month ago 3

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!

This no longer works in UVS (Unity.VisualScripting), so in case Google brought you here, let me save you from hours of trouble trying to figure that one out.

PS: I only pulled that off after some major help from the amazing guys at Bolt's Discord. All credits to them!

private void Update()
foreach(IState iState in _stateMachine.nest.graph.states)
IGraphElement iGraphElement;
IGraphElementData iGraphElementData;

_stateMachine.nest.graph.elements.TryGetValue(iState.guid, out iGraphElement);
_stateMachine.graphData.TryGetElementData((IGraphElementWithData)iGraphElement, out iGraphElementData);

var data = (State.Data)iGraphElementData;

if (data.isActive)
CurrentStateTitle = ((IGraphNester) iState).nest.graph.title;