Hello Community,
I’m trying to get an Actor subclass from a Data Table, in order to spawn it afterwards whenever I need it. Let me explain the process of how I’m doing it, since the error (bug?) is quite funny and I don’t have a clue of why this happens. The Data Asset struct is quite simple, it only contains a TSubclassOf, which is the one I want to store in the asset:
UCLASS()
class CHARACTERMODULE_API UMainCharacterDataAsset : public UPrimaryDataAsset
{
GENERATED_BODY()
public:
UPROPERTY(EditDefaultsOnly, BlueprintReadOnly, Category = "Spawn Info")
TSubclassOf<AActor> MainCharacter;
virtual FPrimaryAssetId GetPrimaryAssetId() const override;
};
In the cpp file I have overridden the GetPrimaryAssetId function in order to work with UE’s Asset Manager:
FPrimaryAssetId UMainCharacterDataAsset::GetPrimaryAssetId() const
{
return FPrimaryAssetId(“MainCharacter”,GetFName());
}
And I have also included the data asset path in Project Settings/Asset Manager section. Then I create the asset in the editor, and select my actor from the content browser. In order to check everything works, I load the actor class from the data asset using a simple static function:
TSubclassOf<AActor> UCharacterStaticsCPP::GetmainCharacterClass(FName AssetName){
UAssetManager& AssetManager = UAssetManager::Get();
FPrimaryAssetId MainCharacterAssetId = FPrimaryAssetId("MainCharacter",AssetName);
UMainCharacterDataAsset* MainCharacterDataAsset = AssetManager.GetPrimaryAssetObject<UMainCharacterDataAsset>(MainCharacterAssetId);
return MainCharacterDataAsset->MainCharacter;
}
If I use this function without closing the Editor, it works nicely. I’m able to load the Class from the Asset, and I’m even able to spawn the actor via blueprints without any problem.
However, here is the thing: If I save all, and then close the editor, when I re-open the project and hit Play, the editor crashes. After doing some c++ debugging, I have found that misteriously the pointer to the class inside the Data Asset is a null (this is, MainCharacterDataAsset->MainCharacter is a nullptr, even though MainCharacterDataAsset exists). However, if you open the Data Asset in the editor, you can clearly see the class. Moreover, if you reset it by hand and hit play… it works again! But of course, if you close and hit play, it crashes once more.
It is like the pointer to the class doesn’t exist inside the Data Asset, until you open the Data Asset in the editor (and then the engine sets the class pointer).
Any thoughts about this?
Thank you in advance guys!