[UE4]C++中SpawnActor用法(動態建立Actor)

C++中建立一個Level並添加的Runtime當中html

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

 

C++中Spawn一個基於藍圖的Actor函數

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

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.this

.hspa

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

.cpp(注意,這段代碼必須放在構造函數中。UE4其餘類型的藍圖,好比Widget藍圖,均可以經過下面這種方式加載。)code

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; } } 

PutNameHere is 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 choosing Copy Reference. Then, just paste that in between the quotes.htm

Now, you're ready to spawn the blueprint. You can do it in BeginPlay() or wherever, just not in the constructor.(這段代碼必須放在非構造函數中,好比BeginPlay()中blog

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.get

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 as YC->SomeVariable = SomeValue. Hope that helps.it

APuzzleBlock* NewBlock = GetWorld()->SpawnActor<APuzzleBlock>(BlockLocation, FRotator(0,0,0));
相關文章
相關標籤/搜索