Download

How to find an asset dynamically?

Hi,

I have a problem with finding assets based on a string path.

Lets say I have a class that has a UTexture2D* member. Also there is a function which is supposed to assign an asset to this pointer.


UTexture2D* Tex;

void SetData(FString AssetPath);
{

    static ConstructorHelpers::FObjectFinder<UTexture2D> TexObj(...???????...);
    Tex = TexObj.Object;
}

In all examples about the ConstructorHelpers I could find, all of them were using these hardcoded paths in a TEXT macro, like:


static ConstructorHelpers::FObjectFinder<UTexture2D> TexObj(TEXT("hard coded path"));

But that’s not what I want to do.

I tried converting the FString to an FText like this:


FText Foo = FText::FromString(AssetPath);
static ConstructorHelpers::FObjectFinder<UTexture2D> TexObj(Foo);
Tex = TexObj.Object;

But that doesn’t compile…

So how can I find an asset without hard coded paths?
Any help is appreciated :slight_smile:

Cheers,
Klaus

Look at UObjectGlobals. You can use LoadObject.




UTexture2D* DynamicTextureLoad = LoadObject<UTexture2D>(GetTransientPackage() /*Or whatever you want to be the outer/owner of this asset*/, AssetPath);
if (DynamicTextureLoad)
{
// ...
}


@ExtraLifeMatt

I look into it… BTW, why is your UTexture2D DynamicTextureLoad not a pointer?
(Still learning C++)

It should be. I just wrote that quickly :slight_smile: The compiler would have yelled about that if you went to compile it.

@ExtraLifeMatt

After a bit of digging, I found that the following at least compiles. but haven’t tested yet if its actually doing what it is supposed to do:


TArray<FString> DataItems;
static ConstructorHelpers::FObjectFinder<UTexture2D> TexObj(*FString("Texture2D'/Game/"+DataItems[2]+"'"));

In this case, the asset path part “TextureFolder/AssetName” is stored in the FString array.
It seems that ‘*FString’ gives you that TCHAR stuff that TEXT() really likes… I tried and at least no error.

Any insights on that? :slight_smile:

I’m not sure what you’re asking.

ConstructorHelpers can only be executed in the constructor of a class when you know the path at compile time. So, if you already know that asset - then that’s fine, but if you don’t then you’ll need to use LoadObject.

If you’re asking how to concatenate the string, then it should be simple.




FString AssetPath = TEXT("/Game/");
AssetPath += DataItems[2];

// Or

FString AssetPath = FString::Printf(TEXT("/Game/%s"), *DataItems[2]);


I was just wondering if *FString would indeed return the desired data and not some nonsensical values.
But yeah, I can only use this in a constructor. Not exactly where I need it, but in another scenario it will come in handy.
So Im reading into how to use LoadObject :slight_smile:

*FString will return a TCHAR pointer. So, yea, it’s valid.

*FString is pretty analogous to std::string.c_str();