In UE5, I can use CreateDefaultSubobject to create a subobject within the constructor of e.g. an actor. But, how do I create an object later, for example in PreInitializeComponents?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
In Unreal Engine 5 (UE5), CreateDefaultSubobject is indeed used within the constructor of a UObject-derived class (like an actor) to create components that are integral to the functionality of the object and require serialization, such as a Mesh Component or a Collider.
However, if you need to create objects at a later stage in the object's lifecycle—outside the constructor where CreateDefaultSubobject is not appropriate—you can use the NewObject function. This function can be used to dynamically create instances of objects at runtime. You might use this in functions like BeginPlay, PreInitializeComponents, or others depending on your needs.
Here's an example of how you might use NewObject in PreInitializeComponents:
cpp
void MyActor::PreInitializeComponents()
{
Super::PreInitializeComponents();
// Only create the component if it's not already created.
if (!MyDynamicComponent)
{
MyDynamicComponent = NewObject<UMyComponentClass>(this, UMyComponentClass::StaticClass());
if (MyDynamicComponent)
{
// Optionally set any properties on the component
MyDynamicComponent->SetSomeProperty(SomeValue);
// Register the component with the actor
MyDynamicComponent->RegisterComponent();
// If you need to attach it to a specific component
MyDynamicComponent->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
}
}
}
When using NewObject, you'll need to specify the class of the object you want to create, and optionally, the outer object if you want to establish ownership (in this case, this to denote the actor owns the component). After creating the object, you should check if the creation was successful before using it. Additionally, if it's a component that should be part of the actor's hierarchy, you'll need to manually register it with RegisterComponent, and if necessary, attach it to other components.
Remember that objects created this way won't be automatically serialized or visible in the editor like those created with CreateDefaultSubobject. They are runtime objects and will exist only while the game is running or until they are explicitly destroyed.