Change State via Code

Thomas S. 2 weeks ago updated 2 weeks ago 3


I'm currently working on a SaveGame-System for my game. Now I've the problem that I also would like to persist the state of my state-machine. It is about this one:

As you can see, the State "Drive Back" is active. Now imagine my game would save at this point. I'd like to store the information, that I'm in this state and continue there after loading. 

Is there a "Best Practice" to do that? Cause at this point I couldn't figure out how to do it via code (doing it via code would be my preferred solution).

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

Since state machines can be near infinitely nested (see super states) there's no straightforward way of telling which state is active via code. You have to do your own state detection logic, for example, with a bool that's set on enter and on exit state.

I think the easiest approach would be to have seperate transitions from an Any State unit and disregard having a start state. When you are in any of your states, On Enter can assign a Save Variable via a string. If the string is not assigned on start do trigger a custom event for the initial state, else you can trigger the state you last saved by just getting the string from the save variable.

if you want to just use a Start State instead of an Any, the same behaviour can be achieved, and triggered without relying on another event doing the initial trigger.

Edit: forgot you prefer code, but unfortunately you can't just inject the save variables into states via code at runtime. The only code option I can think of is triggering transitions in code with CustomEvent.Trigger, and assigning the save variable on the next line with Variables.Saved.Set(string name, object value). If you created a semi generic way of setting and getting that data together, you won't have to do this every time manually.


Thanks for the answers. I know that StateMachines can become really complex and expected that doing it via code might won't work. So (I think) I came to the same solution as you two recommended me. 

I've added another state as entry point. Actually I've expected it to look like a mess but it in the end I'm pretty happy with it: 

It is doing exactly the same as the code would've done. If the cargo of a car is empty then it should go to the state "At Owner" - otherwise the car should "Drive Back". 

So my first transition looks like this:

When I started doing this within the StateMachine I wasn't sure if I will like it. But now it turns out that THIS is my preferred solution and not code. Because it has some clear advantages:

  • My Save-System doesn't have to know about StateMachine and its internals (like name of the states!)
  • It is more bullet proof (StateNames can change. And one can forgot that they're used in code)
  • It is less complex

Edit: Can't see a button like "Mark as solved". But for me the question is answered :-)