Tag Archives: Actor)

C++: The usage of spanactor in [UE4]

create a level in C + + and add it to the runtime

Level.Add(GetWorld()->SpawnActor<ABuildingModLevel>());

Spawn a blueprint-based Actor in C++

https://answers.unrealengine.com/questions/60897/spawn-actorobject-from-code.htm

Here is how I spawn a blueprint via C++. Note that the blueprint I spawn has a base class that was created in C++ also.

.h

TSubclassOf<YourClass> BlueprintVar; // YourClass is the base class that your blueprint uses 

. CPP (note that this code must be placed in the constructor. Other types of UE4 blueprints, such as widget blueprints , can be loaded in the following way.)

ClassThatWillSpawnTheBlueprint::ClassThatWillSpawnTheBlueprint(const class FPostConstructInitializeProperties& PCIP)  
    : Super(PCIP)  
{  
    static ConstructorHelpers::FObjectFinder<UBlueprint> PutNameHere(TEXT("Blueprint'/Path/To/Your/Blueprint/BP.BP'"));  
    if (PutNameHere.Object)   
    {  
        BlueprintVar = (UClass*)PutNameHere.Object->GeneratedClass;  
    }  
}  

PutNameHereis just an arbitrary name you give to the constructor helper. The path to your blueprint is found by finding your blueprint in the content browser, right clicking it, and choosingCopy Reference. Then, just paste that in between the quotes.

Now, you’re ready to spawn the blueprint. You can do it in BeginPlay() or wherever, just not in the constructor.(This code must be placed in a non-constructor, such as BeginPlay())

UWorld* const World = GetWorld(); // get a reference to the world  
if (World)   
{  
    // if world exists  
    YourClass* YC = World->SpawnActor<YourClass>(BlueprintVar, SpawnLocation, SpawnRotation);  
}  

If you don’t know your SpawnLocation or SpawnRotation you can just throw in FVector(0,0,0) and FRotator(0,0,0) instead.

So, since your blueprint base class was also created in C++ this makes it easy to interact with your blueprint from code. It’s as simple asYC->SomeVariable = SomeValue. Hope that helps.

APuzzleBlock* NewBlock = GetWorld()->SpawnActor<APuzzleBlock>(BlockLocation, FRotator(0,0,0));