我们学习ue 都知道,它可以通过虚幻引擎编辑器,直接将一个Actor 蓝图类 拖入世界中,但是我们如何用c++代码来实现这一点呢。
虚幻官方文档其实已经有说明了
https://docs.unrealengine.com/4.27/en-US/ProgrammingAndScripting/SpawnAndDestroyActors/
不过我还是来简单明了一下
关键函数就是 SpawnActor<T>()
它是UWorld类里面的东西
我们来看看官方文档
我们可以看到有7个这个名字的函数
5个模板函数,2个普通函数 用哪一个?
来看看官方文档使用的例子:
GetWorld()->SpawnActor<AActorToSpawn>(SpawnLocation,SpawnRotation);
模板函数 且两个参数
分析一下 应该是上述第四个
字面意思来看 第一个参数是位置的向量 第二个叫什么旋转向量 都是在世界空间的 这里面要扯到矩阵数学了 先不管 这个就是你要在世界生成的位置 和 物品方向
来看第三个参数
FActorSpawnParametersStruct
官方文档的解释是
傳遞給 SpawnActor 函數的可選參數的結果
啥意思呢 我们还是去看看详细
东西很多 比如生成时的物理碰撞问题 就类似于这个东西
GetWorld()->SpawnActor<AActorToSpawn>(SpawnLocation,SpawnRotation);
关键就是
SpawnActor<物品类>(物品在世界位置,物品在的世界方向);
如我们设置一个输入映射
PlayerInputComponent->BindAction("SpawnActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::SpawnActors);
PlayerInputComponent->BindAction("DestroyActors", IE_Pressed, this, &ASpawnDestroyCppCharacter::DestroyActors);
}
按 1 就会调用 ASpawnDestroyCppCharacter::SpawnActors()这个函数
按2 就会调用
ASpawnDestroyCppCharacter::DestroyActors()这个函数
函数实现:
void ASpawnDestroyCppCharacter::SpawnActors()
{
GetWorld()->SpawnActor<物品类>(物品在世界位置,物品在的世界方向);
}
void ASpawnDestroyCppCharacter::DestroyActors()
{
TArray<AActor*> FoundActors; 保存当前运行在世界中的 actor
UGameplayStatics::GetAllActorsOfClass(GetWorld(), 物品类::StaticClass(), FoundActors);
for (AActor* ActorFound :FoundActors)
{
ActorFound->Destroy(); 这是销毁actor
}
}
函数解释
UGameplayStatics::GetAllActorsOfClass()
查找世界中指定類別的所有 Actor。 這是一個緩慢的操作,請謹慎使用,例如 不要使用每一幀。
也就是说 这东西是查找相同类的actor的
GetWorld() 获取世界
StaticClass() 返回一個在運行時表示此類的 UClass 對象 人话就是 返回actor 的类类型
TArray<AActor*> FoundActors;
保存世界里符合当前指定actor 类型的所有actor 对象
UGameplayStatics::GetAllActorsOfClass(GetWorld(), 物品类::StaticClass(), 保存存在在世界里的当前类型的actor的数组);
UGameplayStatics::GetAllActorsOfClass 这个就可以让我们 找到一个世界里摆放的物品 然后根据这个物品的位置,旋转 来相对位置生成我们需要的actor 类
总结
在世界中生成actor SpawnActor<物品类>()
GetWorld()->SpawnActor<物品类>(物品在世界位置,物品在的世界方向);
在世界中销毁actor Destroy()
TArray<AActor*> FoundActors; 保存当前运行在世界中的 actor
UGameplayStatics::GetAllActorsOfClass(GetWorld(), 物品类::StaticClass(), FoundActors);
for (AActor* ActorFound :FoundActors)
{
ActorFound->Destroy(); 这是销毁actor
}