How can I assign a data asset from the editor to a variable in code?

Hey folks, I’m trying to assign a data asset I’ve defined in the editor to a variable in code. I’ve never really worked with data assets in code, and I’m mostly experimenting so I’m not even sure this is a recommended way to do things.

I’ve created a UPrimaryDataAsset class called ItemPrimaryDataAsset. In the editor I created and defined a data asset derived from that class. In code I’ve declared a pointer like this:

	UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category ="Default Item")
	UItemPrimaryDataAsset* EquippedDefaultItem;

Keep in mind I’m specifically trying to set it in code.

Then in the .cpp I tried a few ways, but nothing seems to work. I tried using constructor helpers , but got stuck at this error:

'=': cannot convert from 'TObjectPtr<T>' to 'UItemPrimaryDataAsset *'

Any suggestions?

Do you have the header of your UItemPrimaryDataAsset included ?

I assume there’s a reason why you cannot just change VisibleAnywhere to EditAnywhere?

Anyway, to answer your question, you can try:

const FSoftObjectPath DataAssetPath(FString(“/Game/Folder/SubFolder1/SubFolder2/BP_DataAsset.BP_DataAsset”));
EquippedDefaultItem = Cast< UItemPrimaryDataAsset>(DataAssetPath.TryLoad());

This leaves you with a hard-coded path which might not be the best on some cases but if the reason that you are “specifically trying to set it in code” is just to avoid hard reference to the asset, you can also expose FSoftObjectPath on the editor (or just use TSoftObjectPtr).

1 Like

Excellent! This put me on the right track. I had to make a couple of changes since the asset in the editor was derived from a primary data asset but was of type data asset. This is definitely a bad way to do this. Thanks for the help!

if(!EquippedDefaultItem)
{
const FSoftObjectPath DefaultItemPath(TEXT("/Game/Data/DA_Defaults/DA_DefaultItem"));
EquippedDefaultItem = Cast<UDataAsset>(DefaultItemPath.TryLoad());
};

// Then later in a Switch Case
EquippedItem = Cast<UItemPrimaryDataAsset>(EquippedDefaultItem);

Any reason to use FString instead of TEXT?

oh, right, TEXT is actually better since it’s a literal string.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.