Home [UE] TsubclassOf
Post
Cancel

[UE] TsubclassOf

TsubclassOf에 대해 제가 해석한 내용을 담고 있습니다.
틀린 부분은 댓글로 적어서 공유해 주시면 감사하겠습니다 

공식 문서

TSubclassOf

공식 문서에도 설명이 잘 되어 있는데 처음에는 잘 와닿지 않았다.

나름대로 해석해봤을 때는 언리얼에서 간혹 UClass* 타입을 파라미터로 가지는 메서드들이 있다.

예를 들어, SpawnActor() 메서드를 보면 첫 번째 파라미터에 UClass*를 가지고 있다.

1
2
3
4
5
6
/** Templated version of SpawnActor that allows you to specify the class type via parameter while the return type is a parent class of that type */
template< class T >
T* SpawnActor( UClass* Class, const FActorSpawnParameters& SpawnParameters = FActorSpawnParameters() )
{
    return CastChecked<T>(SpawnActor(Class, NULL, NULL, SpawnParameters),ECastCheckedType::NullAllowed);
}

그래서 만약 아래와 같이 Aweapon* weapon 값을 받아 SpawnActor() 메서드 파라미터에 값을 전달하게 되면

아래와 같은 컴파일 에러가 발생한다.

1
2
3
4
5
6
7
void APlayerCharacter::AttachWeapon(AWeapon* weapon) const
{
	if (weapon)
	{
		AWeapon* spawnWeapon = GetWorld()->SpawnActor<AWeapon>(weapon);
	}
}

img

그래서 UClass* 타입으로 변수 선언이 필요한데 아래와 같이 A 변수를 선언하게 된다면

1
2
UPROPERTY(EditAnyWhere, Category = "Weapon", meta = (AllowPrivateAccess = "true"))
class UClass* _weapon;

디테일 창에서 수 많은 객체들이 노출되는 걸 확인할 수 있다. 

img_1

이러면 잘못된 객체를 지정하는 휴먼 에러가 발생할 수 있다.

**이를 방지하기 위한 방법이 바로 TsubclassOf이다.**

정말 그러한지 확인해보자.

코드를 아래와 같이 수정하고 컴파일 후 확인해 보면

디테일 창에 Aweapon에 해당하는 객체만 노출되는 것을 확인할 수 있다.

1
2
UPROPERTY(EditAnyWhere, Category = "Weapon", meta = (AllowPrivateAccess = "true"))
TSubclassOf<class AWeapon> _weapon;

img_2

This post is licensed under CC BY 4.0 by the author.