Spawning an actor from just the path in c++

I’ve seen a bunch of similar questions but every one has a different or slightly-outdated answer. I know I can use a list of class references to do this without strings, but humour me.

The following works, but only in the editor. In a win64 build, the checkf fails:

static const FSoftObjectPath BlockPath(TEXT("Blueprint'/Game/Cas/BuildingBlock.BuildingBlock'"));
const auto BlockObject = UAssetManager::GetStreamableManager().LoadSynchronous(BlockPath);
checkf(BlockObject != nullptr, TEXT("expected non-null class"));
const auto& BlockClass = Cast<UBlueprint>(BlockObject)->GeneratedClass;
GetWorld()->SpawnActor(BlockClass, &SpawnPos);

I’ve added the Cas directory to “Additional Asset Directories to Cook” in the project’s Packaging settings, but I know this block is already used in the level anyway.

I’ve also tried using my own FStreamableManager, using ResolveObject() on the FSoftObjectPath, and using EngineUtils::FindOrLoadAssetsByPath to similar non-effects.

I’ve also tried with this approach, which also fails in builds but works in the editor:

const auto BlockObject = Cast<UBlueprint>(StaticLoadObject(UBlueprint::StaticClass(), nullptr, TEXT("/Game/Cas/BuildingBlock")));
checkf(BlockObject != nullptr, TEXT("expected non-null class"));
const auto& BlockClass = BlockObject->GeneratedClass;

…which is weird because I’ve used that elsewhere in the codebase to load textures.

What else can I try? What more info can I give you?

1 Like

For a blueprint you’d want to use FSoftClassPath instead of FSoftObjectPath, and you then need to append "_C" to the end of your object’s path. You can then use FSoftClassPath::TryLoadClass to load and get your UClass pointer, which you can pass to SpawnActor

So maybe something like this, I think:

const FSoftClassPath BlockPath(TEXT("/Game/Cas/BuildingBlock.BuildingBlock_C"));
const UClass* BlockClass = BlockPath.TryLoadClass();
checkf(BlockClass != nullptr, TEXT("expected non-null class"));
GetWorld()->SpawnActor(BlockClass, &SpawnPos);
2 Likes

TryLoadClass needs a template param, and UObject worked for me. now it loads everywhere!

I want to create a blueprint.

Solution (A)
Exmaple: Key press = spawn actor from PATH /Game/Cas/BuildingBlock.BuildingBlock_C

Solution (B)
Key press = spawn actor from PATH of widget textbox.

Can you help me please? Maybe you want to create the Logic in EventGraph and send me the C++ code for copy/paste.
I’m not advanced in UE4.
Thanks a lot of your help.