In Unreal Engine 5 (UE5), you can create a new object later, such as in the PreInitializeComponents() function, by using the NewObject() function.
Here's an example of how to create a new AActor as a subobject in the PreInitializeComponents() function:
- First, modify your
UMyCustomActor class header file to include the new subobject you want to create:
// MyCustomActor.h
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MyCustomComponent.h"
#include "MyCustomActor.generated.h"
UCLASS()
class MYPROJECT_API AMyCustomActor : public AActor
{
GENERATED_BODY()
public:
UPROPERTY(EditAnywhere)
UMyCustomComponent* MyCustomComponent;
};
- In the
PreInitializeComponents() function, create a new instance of the subobject:
// MyCustomActor.cpp
#include "MyCustomActor.h"
void AMyCustomActor::PreInitializeComponents()
{
Super::PreInitializeComponents();
// Create a new UMyCustomComponent
UMyCustomComponent* NewCustomComponent = NewObject<UMyCustomComponent>(this, USMyCustomComponent::StaticClass(), NAME_None, RF_Transactional);
// Set the new component as a subobject
NewCustomComponent->SetupAttachment(RootComponent);
NewCustomComponent->RegisterComponent();
// Replace the default subobject with the new one
MyCustomComponent = NewCustomComponent;
}
Replace UMyCustomComponent with the class of the component you want to create, and make sure the UMyCustomComponent class is included in the header file.
In the example, we create a new instance of UMyCustomComponent, set it up as a child of the RootComponent, and register it as a component. Finally, we assign the new component to the MyCustomComponent property.
Remember to include your custom component in the header or source file for the AActor class, or it won't be recognized.