본문 바로가기
Unreal/Component

[Unreal] Component 추가

by 카피마스터 2023. 10. 16.

액터의 생성자에서 추가

1. 액터 멤버 변수로 컴포넌트 포인터를 선언

2. 액터 생성자에서 CreateDefaultSubobject로 컴포넌트를 생성하고 선언한 포인터에 설정

3. 컴포넌트를 루트 컴포넌트로 설정

4. 부모 - 자식관계를 설정하는 경우 자식컴포넌트->SetupAttachment(부모컴포넌트)로 관계를 설정

 

.h

// Fill out your copyright notice in the Description page of Project Settings.

#pragma once

#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "MTObstacle.generated.h"

UCLASS()
class PATHFINDTEST_API AMTObstacle : public AActor
{
	GENERATED_BODY()
	
public:	
	// Sets default values for this actor's properties
	AMTObstacle();

protected:
	// Called when the game starts or when spawned
	virtual void BeginPlay() override;

public:	
	// Called every frame
	virtual void Tick(float DeltaTime) override;

protected:
	// 메인 메쉬 컴포넌트
	UPROPERTY(Editanywhere, Category = "Mesh Setting")
	class UStaticMeshComponent* MainMesh = nullptr;

	// 서브 메쉬 컴포넌트
	UPROPERTY(Editanywhere, Category = "Mesh Setting")
	class UStaticMeshComponent* SubMesh = nullptr;
};

선언한 컴포넌트는 에디터 상에서 설정할 수 있도록 Editanywhere로 설정

.cpp

#include "MTObstacle.h"
#include "Components/StaticMeshComponent.h"

// Sets default values
AMTObstacle::AMTObstacle()
{
 	// Set this actor to call Tick() every frame.  You can turn this off to improve performance if you don't need it.
	PrimaryActorTick.bCanEverTick = true;

	// 메쉬 컴포넌트 생성
	MainMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MainMesh"));
	SubMesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("SubMesh"));

	// 루트 컴포넌트 설정
	RootComponent = MainMesh;

	// 서브 메쉬를 메인 메쉬의 자식으로 설정
	SubMesh->SetupAttachment(MainMesh);
}

// Called when the game starts or when spawned
void AMTObstacle::BeginPlay()
{
	Super::BeginPlay();
}

// Called every frame
void AMTObstacle::Tick(float DeltaTime)
{
	Super::Tick(DeltaTime);
}

 

CreateDefaultSubobject로 UStaticMeshComponent를 생성하여 선언한 멤버 변수에 설정

 

"MainMesh"과 "SubMesh은 액터에서 해당 컴포넌트를 식별하는 식별자

이 식별자를 멤버 변수와 동일하게 맞추지 않으면 생성자 이후 멤버변수가 null로 설정되기 때문에 멤버 변수이름과 동일하게 맞춰준다

 

다음과 같은 형태로 식별자를 통해 컴포넌트를 참조할 수 있다

UStaticMeshComponent* findMeshComponent = Cast<UStaticMeshComponent>(GetDefaultSubobjectByName(TEXT("MainMesh")));

 

 

'Unreal > Component' 카테고리의 다른 글

[Unreal] Component 종류  (0) 2023.10.16