필요한 이유:
초기 구상
.h
UCLASS()
class TESTLAB_PROJECTVM_API UVMLoadManager : public UGameInstanceSubsystem
{
GENERATED_BODY()
public:
// 데이터 매니저 초기화 함수
virtual void Initialize(FSubsystemCollectionBase& Collection) override;
// 데이터 테이블에서 특정 행을 가져오는 함수
struct FVMNPCTalk* GetNPCTalkRow(FName RowName);
struct FVMNPCData* GetNPCDataRow(FName RowName);
private:
// 테이블 데이터 가져오기 템플릿 함수
template<typename T>
T* GetTableRow(UDataTable* Table, FName RowName, const TCHAR* TableName)
{
//RowName에 해당하는 데이터 찾기
T* RowData = Table->FindRow<T>(RowName, TableName);
if(RowData== nullptr)
{
UE_LOG(LogTemp, Log, TEXT("Row %s not found in table %s"), *RowName.ToString(), TableName);
return nullptr;
}
return RowData;
}
private:
class UDataTable* NPCTalkDataTable;
class UDataTable* NPCDataTable;
};
.cpp
void UVMLoadManager::Initialize(FSubsystemCollectionBase& Collection)
{
Super::Initialize(Collection);
UDataTable* LoadedTable = LoadObject<UDataTable>(nullptr, TEXT("/Game/Blueprints/GameData/VMNPCTalkTable.VMNPCTalkTable"));
if (LoadedTable)
{
UE_LOG(LogTemp, Log, TEXT("NPCTalkDataTable Loaded Successfully"));
NPCTalkDataTable = LoadedTable;
}
else
{
UE_LOG(LogTemp, Error, TEXT("Failed to Load NPCTalkDataTable"));
}
LoadedTable = LoadObject<UDataTable>(nullptr, TEXT("/Game/Blueprints/GameData/VMNPCDataTable.VMNPCDataTable"));
if (LoadedTable)
{
UE_LOG(LogTemp, Log, TEXT("NPCDataTable Loaded Successfully"));
NPCDataTable = LoadedTable;
}
else
{
UE_LOG(LogTemp, Error, TEXT("Failed to Load NPCDataTable"));
}
}
FVMNPCTalk* UVMLoadManager::GetNPCTalkRow(FName RowName)
{
return GetTableRow<FVMNPCTalk>(NPCTalkDataTable, RowName, TEXT("NPCTalkDataTable"));
}
FVMNPCData* UVMLoadManager::GetNPCDataRow(FName RowName)
{
return GetTableRow<FVMNPCData>(NPCDataTable, RowName, TEXT("NPCDataTable"));
}
리팩토링
.h
UCLASS()
class TESTLAB_PROJECTVM_API UVMLoadManager : public UGameInstanceSubsystem
{
GENERATED_BODY()
public:
// 데이터 테이블에서 특정 행을 가져오는 함수
struct FVMNPCTalk* GetNPCTalkRow(FName RowName);
struct FVMNPCData* GetNPCDataRow(FName RowName);
private:
// 테이블 데이터 가져오기 템플릿 함수
// UDataTable *& Table 로 원본값 갱신
template<typename T>
T* GetTableRow(UDataTable*& Table, const TCHAR* TablePath, FName RowName, const TCHAR* TableName)
{
// 테이블이 로드되지 않은 경우 로드 시도
if (Table == nullptr)
{
Table = LoadObject<UDataTable>(nullptr, TablePath);
if (Table != nullptr)
{
UE_LOG(LogTemp, Log, TEXT("%s Loaded Successfully"), TableName);
}
else
{
UE_LOG(LogTemp, Error, TEXT("Failed to Load %s"), TableName);
return nullptr;
}
}
//RowName에 해당하는 데이터 찾기
T* RowData = Table->FindRow<T>(RowName, TableName);
if(RowData== nullptr)
{
UE_LOG(LogTemp, Log, TEXT("Row %s not found in table %s"), *RowName.ToString(), TableName);
return nullptr;
}
return RowData;
}
private:
class UDataTable* NPCTalkDataTable;
class UDataTable* NPCDataTable;
};