I have created a mirror system which rapidly spawns and destroys actors however whenever i try to spawn multiple at once and then destroy them soon after, my engine completely freezes up and i have to close it via task manager.
Heres my code for iterating through the array of pointers to spawned actors
for (int index = 0; index < Lasers.Num(); index++)
{
GEngine->AddOnScreenDebugMessage(index, 30.f, FColor::Red, FString(Lasers[index]->GetName()));
if (!Lasers[index]) return;
if (!Lasers[index]->IsValidLowLevel()) return;
Lasers[index]->K2_DestroyActor();
Lasers[index] = NULL;
}
Lasers.Empty();
Heres how i am spawning actors and adding them to the TArray
// Fill out your copyright notice in the Description page of Project Settings. #include “Laser.h” #include “Beam.h” #include “DrawDebugHelpers.h” #include “EngineUtils.h” #include “CollisionQueryParams.h” #include “Kismet/GameplayStatics.h” #include “Math/Vector.h”
// Sets default values
ALaser::ALaser()
{
// 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;
// Called when the game starts or when spawned
void ALaser::BeginPlay()
{
Super::BeginPlay();
GetWorld()->GetTimerManager().SetTimer(StartLaserTimer, this, &ALaser::StartCast, 0.01f, true);
}
// Called every frame
void ALaser::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
This will potentially be really bad for performance. You might lock up the game-thread during the loop causing a stall, as well as creating too many actors before the previous ones are can be garbage collected can cause an Out of Memory crash.
In general for something like this you may either want to use instanced static meshes or Niagara particles, instead of multiple Actors. This will be better for performance and memory consumption. If you really do need to create many actors, you might benefit from doing that asynchronously, via a parallel for loop.