So, I am trying to make a spawn system to my game so the enemies will automatically spawn when i get close to a target point and only one enemy can be in the scene per target point, but whenever I run the game with this code the editor instantly crashes and I can’t figure out why. I’ve made some tests and the problem is definitely in the SpawnEnemy function, but not bellow the second if.
.cpp file:
#include "CUGameMode.h"
#include "BOTEnemy.h"
#include "Kismet/GameplayStatics.h"
#include "Engine/World.h"
#include "Public/TimerManager.h"
#include "Engine.h"
ACUGameMode::ACUGameMode()
{
PrimaryActorTick.bCanEverTick = true;
}
void ACUGameMode::BeginPlay()
{
Super::BeginPlay();
UGameplayStatics::GetAllActorsOfClass(GetWorld(), SpawnerClass, Spawners);
}
void ACUGameMode::SpawnEnemy()
{
for (int i = 0; i < Spawners.Num(); i++)
{
if (Spawners[i]->GetDistanceTo(Cast<AActor>(UGameplayStatics::GetPlayerCharacter(GetWorld(), 0))) < 7000.f)
{
if (!SpawnedEnemies[i])
{
FTransform SpawnerTransform = Spawners[i]->GetActorTransform();
EEnemyType SpawnedEnemyType = EEnemyType::Barghest;
if (Spawners[i]->ActorHasTag("BarghestSpawner"))
{
SpawnedEnemyType = EEnemyType::Barghest;
}
SpawnedEnemies[i] = GetWorld()->SpawnActorDeferred<ABOTEnemy>(ClassToSpawn, SpawnerTransform);
SpawnedEnemies[i]->TipoDoInimigo = SpawnedEnemyType;
SpawnedEnemies[i]->FinishSpawning(SpawnerTransform);
}
}
}
}
void ACUGameMode::SpawnerTimer()
{
bCanSpawn = true;
}
void ACUGameMode::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
UGameplayStatics::GetAllActorsOfClass(GetWorld(), ABOTEnemy::StaticClass(), EnemiesSpawned);
if (EnemiesSpawned.Num() < 10 && bCanSpawn)
{
SpawnEnemy();
bCanSpawn = false;
GetWorldTimerManager().SetTimer(SpawnTimer, this, &ACUGameMode::SpawnerTimer, 2.f, false);
}
}
.h file:
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/GameModeBase.h"
#include "CUGameMode.generated.h"
/**
*
*/
UCLASS()
class CU_API ACUGameMode : public AGameModeBase
{
GENERATED_BODY()
private:
virtual void BeginPlay() override;
FTimerHandle SpawnTimer;
TArray<class AActor*> Spawners;
TArray<class AActor*> EnemiesSpawned;
TArray<class ABOTEnemy*> SpawnedEnemies;
UPROPERTY(EditAnywhere, Category = "Class")
TSubclassOf<class AActor> SpawnerClass;
UPROPERTY(EditAnywhere, Category = "Class")
TSubclassOf<class ABOTEnemy> ClassToSpawn;
UFUNCTION()
void SpawnEnemy();
UFUNCTION()
void SpawnerTimer();
bool bCanSpawn = true;
public:
ACUGameMode();
virtual void Tick(float DeltaTime) override;
};