UE4 C++ 的SpawnActor
// Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "SpwanVolume.generated.h"
UCLASS()
class GETSTARTED_API ASpwanVolume : public AActor
{
GENERATED_BODY()
public:
// Sets default values for this actor's properties
ASpwanVolume();
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
class UBoxComponent* SpawnBox; //碰撞盒子
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Spawn Volume")
TArray<TSubclassOf<AActor>> SpawnActorClassesArray;//TSubclassOf 一个模板类
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
public:
// Called every frame
virtual void Tick(float DeltaTime) override;
UFUNCTION(BlueprintPure, Category = "Spawn Volume")
FVector GetSpawnPoint();
UFUNCTION(BlueprintPure, Category = "Spawn Volume")
TSubclassOf<AActor> GetSpwnActorClass();
UFUNCTION(BlueprintNativeEvent, BlueprintCallable, Category = "Spawn Volume")//有了BlueprintNativeEvent后我们的反射系统就会创建出两个东西
void SpawnActor(UClass* SpawnClass,FVector SpawnLocation);
};
// Fill out your copyright notice in the Description page of Project Settings.
#include "Gameplay/SpwanVolume.h"
#include "Components/BoxComponent.h"
#include "Kismet/KismetMathLibrary.h"
// Sets default values
ASpwanVolume::ASpwanVolume()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
SpawnBox = CreateDefaultSubobject<UBoxComponent>(TEXT("SpawnBox"));
RootComponent = SpawnBox;//设置为跟组件
}
// Called when the game starts or when spawned
void ASpwanVolume::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ASpwanVolume::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
FVector ASpwanVolume::GetSpawnPoint()
{
const FVector Origin = SpawnBox->GetComponentLocation();//获取位置
const FVector Extent = SpawnBox->GetScaledBoxExtent();//盒子范围,按组件比例缩放。就是说放到场景后再放大,获取放大的范围
return UKismetMathLibrary::RandomPointInBoundingBox(Origin, Extent); //使用第一个向量作为原点,将第二个向量作为框范围,返回指定边界框中的随机点。
}
TSubclassOf<AActor> ASpwanVolume::GetSpwnActorClass()
{
if (SpawnActorClassesArray.Num() > 0) {//判断集合里有没有对象
int index = FMath::RandRange(0, SpawnActorClassesArray.Num() - 1);
return SpawnActorClassesArray[index];
}
else {
return nullptr;
}
}
void ASpwanVolume::SpawnActor_Implementation(UClass* SpawnClass, FVector SpawnLocation)//这个就像是SpawnActor的父类的版本
{
if (SpawnClass) {
GetWorld()->SpawnActor<AActor>(SpawnClass, SpawnLocation, FRotator(0.0f));
}
}
用蓝图调用C++写好的代码
给公开的变量集合赋值
运行后: