In UE5, I can use CreateDefaultSubobject to create a subobject within the constructor of…
- User
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
In Unreal Engine 5 (UE5),
CreateDefaultSubobjectis indeed used within the constructor of a class derived fromUObjectto create components or other UObject-derived subobjects that are intended to exist for the entire lifetime of the parent object. These subobjects are also automatically replicated, serialized, and integrated into the Unreal Engine's garbage collection system.However, if you need to create an object at a later time, such as during the
PreInitializeComponentsphase or at any point after the constructor has run, you should not useCreateDefaultSubobject. Instead, you can use theNewObjectfunction to dynamically create instances of UObjects.Here's an example of how you might create a component during the
PreInitializeComponentsoverride:void AMyActor::PreInitializeComponents() { Super::PreInitializeComponents(); // Make sure to only do this once and that the component is not already created if (MyDynamicComponent == nullptr) { MyDynamicComponent = NewObject<UMyComponent>(this, UMyComponent::StaticClass()); if (MyDynamicComponent != nullptr) { // Optionally set any properties on the component MyDynamicComponent->SetSomeProperty(SomeValue); // Register the component with the engine so it gets updated/rendered MyDynamicComponent->RegisterComponent(); // If you want to attach it to an existing component, do so here MyDynamicComponent->AttachToComponent(GetRootComponent(), FAttachmentTransformRules::KeepRelativeTransform); } } }In the above example,
MyDynamicComponentis a UPROPERTY member ofAMyActor. It's a pointer that's initially null and gets assigned a newly created instance ofUMyComponentby usingNewObject. After creating the new component, it's registered with the engine usingRegisterComponent, so that it becomes part of the actor's component hierarchy and receives updates. If you want to attach the new component to another component, such as the root component, you would useAttachToComponent.Please note that when you dynamically create components like this, they are not automatically replicated or saved/loaded with the actor unless you set those properties manually. In contrast, components created with
CreateDefaultSubobjectin the constructor are automatically set up for replication and serialization.Always remember to check if the object has already been created before creating a new one to avoid memory leaks and unnecessary object creation.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.