Skip to content

Instantiation and Context

When you design your state machine in the editor you are creating a class. When you use this state machine at run-time you're creating an instance from your class.

Upon creating the instance you pass in an object (typically an actor instance) which serves as a context for this state machine instance.

Design-Time

When designing a state machine blueprint you can reference the object the state machine represents by calling Get Context in any graph and casting it to your object type.

GetContextImage

Think of this as being similar to Try Get Pawn Owner of Animation Blueprints.

Run-Time

To use the state machine at run-time you can either instantiate it as a UObject or Actor Component.

UObjects

You can create the state machine any where by calling the static function Create State Machine Instance. When you do so you must pass in both the class of the state machine and the context.

Instantiate

See Create State Machine Instance.

Memory Management

Remember to assign your instance to a blueprint member variable! If you just create the instance and start it, then it may be garbage collected by Unreal.

.h file
UPROPERTY(BlueprintReadWrite)
USMInstance* StateMachine
.cpp file
StateMachine = USMBlueprintUtils::CreateStateMachineInstance(StateMachineClass, YourContext);

See USMBlueprintUtils::CreateStateMachineInstance.

Memory Management

Remember to assign your instance to a UPROPERTY! If you just create the instance and start it, then it may be garbage collected by Unreal.

Actor Components

State machine components are wrappers for UObjects which also support network replication. By default the actor itself is passed in as the context to the state machine.

Blueprint Component

See the Unreal Documentation on attaching a component in C++.

If you uncheck Initialize on Begin Play make sure to call Initialize on the actor component before starting it.

Garbage Collection

To garbage collect the UObject version all strong references to the instance will need to be cleared, like any other object in Unreal Engine. Calling Shutdown is not necessary to trigger garbage collection for the UObject version.

Calling Shutdown on the component may be necessary so the internal UObject instance can be garbage collected, but only if the owning actor and component are still in use. Otherwise the internal instance will be garbage collected along with the component.