How to toggle states using Variables

Sometimes you need to toggle states, like doors, levers etc. To make one, the best way is often to use a variable. Let's see how to do that. Let's say I have a lever. First you need to think of what states you need. In this case, I need 2: One for when the lever is toggled and when it is not.

Using a main trigger

First you must create a main trigger for toggling the state. I will use the any key pressed condition. As this can stay true for multiple frames, I need to also include a trigger once:

Adding States

Now you need to add the states. Let's use 1 subevent for each state:

Adding a variable to define the current state

Now you need a variable to define the current state. I will name mine “leverState”: And also add events for changing the state correctly depending on the previous state:

Make sure the state can be changed only once per frame

The current code is problemetic: It changes the state to toggled and directly after checks that variable to reswitch it to untoggled. We need to add additional conditions to let the state change happen only once per frame:

The condition in the first state for checking for the Flag saying it was modified and the action for setting the Flag saying it was modified are redundant, but I keep the same conditions and actions on all events for consistency. You can use them or not, depending on what you consider the best practice of removing redudancy and having consistency.