I would like to know how could I, if possible, spawn a Blueprint in editor time. The reason for this is that I am working on a Plugin which should create the whole scene before player can start playing.
I mostly know how to spawn a Blueprint from C++ code but it seems I need the correct World which I do not know how to get. I may need to find the proper context to call GetWorld and receive a valid one but I am not 100% sure about this being the only thing I am doing wrong.
This is the code I am using to spawn:
UWorld* const World = GEngine->GetWorld();
if (World)
{
FActorSpawnParameters SpawnParams;
MyClass* DroppedItem = World->SpawnActor<MyClass>(MyBluePrint, SpawnParams);
}
And this is the definition of the BP I want to spawn:
I spent a lot of time trying to figure this one out myself. To add Actors to a level in the Editor using code you don’t want to Spawn them, instead you want to Add them using UEditorEngine::AddActor(). This is (I assume) what happens when you for example drag and drop a StaticMesh from the Content Browser.
I used a Blutility to do this and they have access to a global called GEditor which is an instance of UEditorEngine. I’m guessing Plugins have the same or something similar available.
Thank you Dieselhead. I had different problems and finally put all my code together and now it works: I can spawn a blueprint from C++ code in editor time. Here I post the code:
FStringAssetReference ItemRef = "Blueprint'/Game/Blueprints/MYBP.MYBP'";
UObject* ItemObj = ItemRef.ResolveObject();
UBlueprint* Gen = Cast<UBlueprint>(ItemObj);
if (Gen && GWorld)
{
static int32 Index = 0;
FActorSpawnParameters SpawnPar;
SpawnPar.Name = *FString::Printf(TEXT("Spawned %d"), Index++);
AActor* Item = GWorld->SpawnActor<AActor>(Gen->GeneratedClass, spawnPar);
if (!Item)
{
UE_LOG(LogPlugin, Warning, TEXT("Could not spawn."));
}
}