UE4 C++ 的SpawnActor
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "SpwanVolume.generated.h"
UCLASS()
class GETSTARTED_API ASpwanVolume : public AActor
{
GENERATED_BODY()
public:
ASpwanVolume();
UPROPERTY(VisibleAnywhere, BlueprintReadOnly)
class UBoxComponent* SpawnBox;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Spawn Volume")
TArray<TSubclassOf<AActor>> SpawnActorClassesArray;
protected:
virtual void BeginPlay() override;
public:
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")
void SpawnActor(UClass* SpawnClass,FVector SpawnLocation);
};
#include "Gameplay/SpwanVolume.h"
#include "Components/BoxComponent.h"
#include "Kismet/KismetMathLibrary.h"
ASpwanVolume::ASpwanVolume()
{
PrimaryActorTick.bCanEverTick = true;
SpawnBox = CreateDefaultSubobject<UBoxComponent>(TEXT("SpawnBox"));
RootComponent = SpawnBox;
}
void ASpwanVolume::BeginPlay()
{
Super::BeginPlay();
}
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)
{
if (SpawnClass) {
GetWorld()->SpawnActor<AActor>(SpawnClass, SpawnLocation, FRotator(0.0f));
}
}
用蓝图调用C++写好的代码
给公开的变量集合赋值
运行后:
|