Skip to content

2.3 Update the State Machine through code

Gabriel Dechichi edited this page Feb 18, 2023 · 3 revisions

Update the State Machine through code

In this section, we'll see how to control the state machine through code.

1. Playing the sample

Open the scene at All Samples/2 - State Machine/2 - Set Parameters Through Code/DMotion - State Machine - SetParameterThroughCode.unity and hit play. If you press Space the robot will toggle between the Walk and Run states.

If you select the LowPolyRobot object, you'll see the AnimationStateMachineAuthoring component. The state machine asset is the exact same we build in the last section. You'll also see a SetParameterThroughCodeAuthoring, which is only being used to manually create the system used in this sample.

image

2. Setting animation parameters through code

The code for this sample should be very straightforward by now, the code is in SetParametersThroughCodeSystem.cs.

[RequireMatchingQueriesForUpdate]
public partial struct SetParametersThroughCodeSystem : ISystem
{
    private static readonly int IsRunningHash = StateMachineParameterUtils.GetHashCode("IsRunning");
    public void OnCreate(ref SystemState state)
    {
        state.RequireForUpdate<SetParametersThroughCodeSample>();
    }
    public void OnDestroy(ref SystemState state)
    {
    }
    
    public void OnUpdate(ref SystemState state)
    {
        var toggleIsRunning = Input.GetKeyDown(KeyCode.Space);

        foreach (var boolParameters in SystemAPI.Query<DynamicBuffer<BoolParameter>>())
        {
            if (toggleIsRunning)
            {
                var currentValue = boolParameters.GetValue<BoolParameter, bool>(IsRunningHash);
                boolParameters.SetValue(IsRunningHash, !currentValue);
            }
        }
    }
}

You'll see that we cache the hash of the IsRunning state, similar to what we did in the Animation Events example. Then we're able to read/write to the bool parameter through the BoolParameter buffer and GetValue and SetValue functions respectively.

It is also possible to use GetValue and SetValue with the parameter name directly, though this is slower than using the hash, since the system will have to calculate the hash for you every frame.

Below are buffers for each state machine parameter:

Parameter DynamicBuffer
Boolen DynamicBuffer
Integer DynamicBuffer
Float DynamicBuffer
Enum (Pro Only) DynamicBuffer (same as int)

3. Conclusion

That's all for the basics of State Machines in DMotion! Feel free to check the Miscellaneous section for other (some advanced) examples.