Skip to content

Instantly share code, notes, and snippets.

@bluebright
Last active January 15, 2026 06:19
Show Gist options
  • Select an option

  • Save bluebright/1bbcc15e56547bf0c3589abbfc1b7b14 to your computer and use it in GitHub Desktop.

Select an option

Save bluebright/1bbcc15e56547bf0c3589abbfc1b7b14 to your computer and use it in GitHub Desktop.
[Unreal Engine][5.3] 컴포넌트 생성 및 초기화
//H
UCLASS()
class AMyActor : public AActor
{
GENERATED_BODY()
public:
AMyActor(const FObjectInitializer& ObjectInitializer);
UPROPERTY()
TObjectPtr<USceneComponent> RootTopComponent;
UPROPERTY()
UStaticMeshComponent* MyStaticMeshComponent;
};
//CPP
AMyActor::AMyActor(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer)
{
//Actor의 생성자 내부에서 정적 Component(UPROPERTY로 지정된 Component)를 초기화하기 위해서는
//CreateDefaultSubobject로 생성해야된다. (이 함수는 액터 생성자 내부에서만 사용해야됨. USceneComponent는 될지도??)
RootTopComponent = CreateDefaultSubobject<USceneComponent>(TEXT("RootTopComp")); //RootComponent는 아무 것이라도 반드시 설정할 것!
SetRootComponent(RootTopComponent); //RootComponent = RootTopComponent; //이거 사용해도 된다.
//다른 Component 설정
MyStaticMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MyStaticMeshComp"));
MyStaticMeshComponent->SetupAttachment(RootComponent); //Register 역할도 해준다
}
/**
* 생성자 내부에서는 RegisterComponent()나 AttachToComponent()가 제대로 동작하지 않을 수 있음.
* Actor 생성자에서는 World가 아직 초기화 중일 수 있다.
* 따라서 아래와 같은 함수는 생성자 아닌 다른 곳에서 호출해야한다.
*/
void AMyActor::AddMyComponent(FString ComponentName)
{
//생성자가 아닌 곳에서 Component를 생성 및 등록을 하기 위해서는
//아래처럼 런타임에서 동적으로 생성(Dynamic Runtime)하는 함수를 사용해야된다.
//NewObject(), RegisterComponent(), AttachToComponent()
//생성자에서는 World (또는 GetWorld())가 아직 초기화되지 않았을 수 있다.
UMyComponent* MyComp = NewObject<UMyComponent>(this, *ComponentName); //여기서 this는 부모가 되는 AMyActor를 의미한다. (컴포넌트가 있는 Actor)
MyComp->RegisterComponent();
MyComp->AttachToComponent(RootComponent, FAttachmentTransformRules::KeepRelativeTransform);
}
/**
* 컴포넌트 내부에서 다른 컴포넌트를 생성 및 초기화는 연구가 필요함 (언리얼 표준이 아니라고 함)
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment