Skip to content
The Chat Archive
gemini-pro· Google Arena Human Preference 55K

In UE5, I can use CreateDefaultSubobject to create a subobject within the constructor of…

  1. 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?

  2. Assistant

    In UE5, to create an object later, for example in PreInitializeComponents, you can use the following steps:

    1. Declare a variable of the object type you want to create in the header file of your class.
    2. In the constructor of your class, initialize the variable to nullptr.
    3. In PreInitializeComponents, create the object using the NewObject function and assign it to the variable.

    Here is an example:

    #include "UObject/ConstructorHelpers.h"
    #include "UObject/UObjectGlobals.h"
    
    UCLASS()
    class UMyActor : public AActor
    {
        GENERATED_BODY()
    
    public:
        // Declare the variable
        UStaticMeshComponent* MyStaticMeshComponent;
    
        UMyActor();
        void PreInitializeComponents() override;
    };
    
    UMyActor::UMyActor()
    {
        // Initialize the variable to nullptr
        MyStaticMeshComponent = nullptr;
    }
    
    void UMyActor::PreInitializeComponents()
    {
        Super::PreInitializeComponents();
    
        // Create the object using the NewObject function and assign it to the variable
        MyStaticMeshComponent = NewObject<UStaticMeshComponent>(this, UStaticMeshComponent::StaticClass());
    }
    

    This will create a UStaticMeshComponent object and assign it to the MyStaticMeshComponent variable in the PreInitializeComponents function.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.