UE4 动态增删查改Actor、BP

发表于2018-02-26
评论0 1.2k浏览

想免费获取内部独家PPT资料库?观看行业大牛直播?点击加入腾讯游戏学院游戏程序行业精英群

711501594
特殊说明:创建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);  
来自:http://blog.csdn.net/OnafioO/article/details/77990787

原文链接

著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引

游戏学院公众号二维码
腾讯游戏学院
微信公众号

提供更专业的游戏知识学习平台