ue4 动态增删查改 actor,bp

ue4.17


特殊说明:创建bp时,如果bp上随手绑一个cube,那么生成到场景的actor只执行构造不执行beginPlay,原因未知


ATPlayerPawn是c++类

直接动态创建actor

UWorld* const World = GetWorld();
FVector v = FVector(0, 0, 0);
FRotator r = FRotator(0, 0, 0);
if (World)
{
	ATPlayerPawn* Player = World->SpawnActor<ATPlayerPawn>(v, r);	
}


建立一个名为TPlayerPawnBP的蓝图,继承ATPlayerPawn

动态创建方法,3方法基本类似,随便记录下

1 可在运行时使用

FStringAssetReference asset = "Blueprint'/Game/bp/TPlayerPawnBP.TPlayerPawnBP'";
UObject* itemObj = asset.ResolveObject();
UBlueprint* gen = Cast<UBlueprint>(itemObj);
if (gen != NULL)
{
	ATPlayerPawn* spawnActor = GetWorld()->SpawnActor<ATPlayerPawn>(gen->GeneratedClass);
}

2 可在运行时使用

UObject* loadObj = StaticLoadObject(UBlueprint::StaticClass(), NULL, TEXT("Blueprint'/Game/bp/TPlayerPawnBP.TPlayerPawnBP'"));
if (loadObj != nullptr)
{
	UBlueprint* ubp = Cast<UBlueprint>(loadObj);
	AActor* spawnActor = GetWorld()->SpawnActor<AActor>(ubp->GeneratedClass);
}

3 先保存蓝图类,然后运行时创建

.h中定义

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "N") 
TSubclassOf<ATPlayerPawn> doorBPClass;
.cpp构造中

static ConstructorHelpers::FClassFinder<ATPlayerPawn> doorBPClassFinder(TEXT("/Game/bp/TPlayerPawnBP"));
if (doorBPClassFinder.Class != nullptr)
{
	UE_LOG(TLog, Warning, TEXT("NMgrActor Construct doorBP!=null"));
	doorBPClass = doorBPClassFinder.Class;
}
.cpp BeginPlay中

UWorld* const World = GetWorld();
if (World) 
{	
	World->SpawnActor<ATPlayerPawn>(doorBPClass);	
}


4 运行时创建,大体思路都一样,只要找到bp类就行,注意这个路径有个_C

TSubclassOf<ATPlayerPawn> TS = LoadClass<ATPlayerPawn>(NULL,TEXT("Blueprint'/Game/bp/TPlayerPawnBP.TPlayerPawnBP_C'"));
GetWorld()->SpawnActor<ATPlayerPawn>(TS);




原文地址:https://www.cnblogs.com/nafio/p/9137065.html