C++中SpawnActor用法(动态创建Actor)
2018-08-27
C++中创建一个Level并添加的Runtime当中
Level.Add(GetWorld()->SpawnActor<ABuildingModLevel>());
C++中Spawn一个基于蓝图的Actor
UWorld* const World = GetWorld(); // get a reference to the world
if (World)
{
// if world exists
YourClass* YC = World->SpawnActor<YourClass>(BlueprintVar, SpawnLocation, SpawnRotation);
}
SpawnActor一般用在非构造函数中,比如BeginPlay()。
如果想在构造函数中创建Actor,一般用ConstructorHelpers::FObjectFinder。例如:
.h
TSubclassOf<YourClass> BlueprintVar;
.cpp
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;
}
}
UE4其他类型的蓝图,比如Widget蓝图,都可以通过下面这种方式加载。