Assets not loading from the AssetRegistry

I have some code that scans the AssetRegistry at start up for certain types of assets. Once It finds one, I then want to add its class default object (CDO) to an array for latter use. The problem is that the assets aren’t always loading for some reason.

Here is some example code of what I’m doing to gather an array of CDO’s for an arbitrary class, MyActor in this example.


// MyActorAssetPath has come from the AssetRegistry after finding a MyActor based asset...
FStringAssetReference StringAssetReference = FStringAssetReference(MyActorAssetPath);
TAssetSubclassOf<MyActor> AssetSubclass = TAssetSubclassOf<MyActor>(StringAssetReference);
UClass* Class = AssetSubclass.LoadSynchronous();
ArrayOfMyActor.Add(Class->GetDefaultObject<MyActor>());

The problem is that LoadSynchronous() on line 3 doesn’t always work. Sometimes it does, and I get a valid UClass pointer, other times it doesn’t and I get a null pointer. It is entirely random whether it works or not.

One thing I have noticed though is that if I open an asset in the editor first before running the project, then that asset will return a valid UClass pointer from LoadSynchronous() when I run the project. Any other assets however will usually return a null pointer. But like I said, this is random as sometimes it all works perfectly, even if I don’t pre-load anything in the editor.

I’m assuming there is some logical explanation behind why this is happening, I just can’t fathom it and am at a loss as to what to do. Does anyone understand what is going on here?

If you .Get() the weak asset references and you execute that code on a module marked to load post engine initialization then your CDO array should work; you are probably doing this while engine is initializing this is why you get random results.

I’m doing it in the player control OnBeginPlay, so I assumed everything would be initialized by then. Guess not?

I don’t know for sure but it’s possible the asset registry asynchronously loads its asset data and the engine doesn’t wait on it. It seems strange, I’ve never had an issue like this, but you could try testing out its state. IAssetRegistry::IsLoadingAssets will tell you if it’s still in progress, or you can call SearchAllAssets passing true to do a full synchronous search.