언리얼엔진5/각종 지식
[UE5] 월드에 액터를 스폰하는 방법 (SpawnActor)
Rocketbabydolls
2024. 6. 12. 01:13
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = Weapon , Meta = (AllowPrivateAccess = "true"))
TSubclassOf<class AActor> PrimaryWeaponBpRef;
if (UWorld* World = GetWorld())
{
if (PrimaryWeaponBpRef != nullptr)
{
// 스폰할 위치와 회전을 지정
FVector SpawnLocation = FVector(0.0f, 0.0f, 0.0f);
FRotator SpawnRotation = FRotator(0.0f, 0.0f, 0.0f);
// 액터 스폰 파라미터 설정
FActorSpawnParameters SpawnParams;
SpawnParams.Owner = this;
SpawnParams.Instigator = GetInstigator();
// 월드에서 액터를 스폰
PrimaryWeapon = Cast<AVIAKWeapon>(World->SpawnActor<AActor>(PrimaryWeaponBpRef, SpawnLocation, SpawnRotation, SpawnParams));
if (PrimaryWeapon)
{
// 스폰된 액터에 대해 추가 작업을 수행
FAttachmentTransformRules AttachmentRules(EAttachmentRule::KeepRelative, true);
PrimaryWeapon->AttachToComponent(FirstPersonMesh, AttachmentRules, FName(TEXT("Palm_R")));
}
}
}
주의할 점은 블루프린트 스폰 시 포인터를 TSubclassof 를 사용해야 한다. 그렇지 않으면 컴파일 오류가 난다.
왜인지 열심히 찾아보았지만 이유는 명확하게 나오지 않았지만, 포인터의 특성상 안정성과 블루프린트와의 연동성을 위한 것 같다.
++) Transform으로 한번에 값을 넘겨주지 않을 것이라면 Scale은 스폰 후 setscale3d로 조절 가능하다.