Loading an asset from Content browser into c++

I want to load a data table in C++. Thus:

	UDataTable* ExcelTable;
	ConstructorHelpers::FObjectFinder<UDataTable> ExcelTable_BP(TEXT(ItemDataTableFilePath));
	UE_LOG(LogTemp, Warning, TEXT("After object finder."));
	ExcelTable = ExcelTable_BP.Object;
	if(ExcelTable == nullptr)
	{
		UE_LOG(LogTemp, Warning, TEXT("Couldn't load item database."));
		return false;
	}
	UE_LOG(LogTemp, Warning, TEXT("After if test."));

I made a static function called “LoadItem” that returned a boolean and a pointer to a newly constructed item (by reference). This continuously crashed on me without fail. Then I did some looking up online and found out this can only ever be called inside of a constructor. So, I shoved this stuff into a constructor for a class, thus:

.h file:

UCLASS()
class MYPROJECT_API UTestConstructor : public UObject
{
	GENERATED_BODY()
	
	public:
	UDataTable* dataTable;
	UTestConstructor(){}
	~UTestConstructor(){}
	UTestConstructor(const TCHAR* objToLoad);
};

.cpp file

UTestConstructor::UTestConstructor(const TCHAR * objToLoad)
{
	UE_LOG(LogTemp, Warning, TEXT("Inside TestConstructor."));
	dataTable = nullptr;
	ConstructorHelpers::FObjectFinder<UDataTable> ExcelTable_BP(objToLoad);
	UE_LOG(LogTemp, Warning, TEXT("After object finder."));
	dataTable = ExcelTable_BP.Object;
	if(dataTable == nullptr)
	{
		UE_LOG(LogTemp, Warning, TEXT("Couldn't load item database."));
	}
}

This crashed immediately when calling this constructor. It didn’t even get to the first line of this code that outputs a log entry.

So, I removed the UObject inheritance from it. Doing that gave me the original crash that I was having when it wasn’t in a constructor.

What am I doing wrong?

You can’t use other constructors to make UObjects, you can use only default one, FObjectFinder staticly loads asset then object is created and can be only used in constructor, there diffrent function to load assets dynamicly. There is type specilly made to hold asset path (in blueprint it called Asset ID, and that path you use in FObjectFinder):

https://docs.unrealengine.com/latest/INT/API/Runtime/CoreUObject/Misc/FStringAssetReference/index.html

Once you establish it you can load and get asset of path that it contains. In you case that would be something like this ( i assume ItemDataTableFilePath is FString):

FStringAssetReference MyAssetPath(ItemDataTableFilePath);
    UObject* MyAsset= MyAssetPath.TryLoad();

Also i think you could change ItemDataTableFilePath from FString to FStringAssetReference

So use FObjectFinder when you want to hard code refrence of asset to the class, if not, if you don’t know what asset that class will use, use this

1 Like

Thank you! Worked like a charm.