Hello,
I have multiple “turrets”, which always look at a target (chosen from a list of targets within their respective ranges). Every seconds they shoot at the target, by spawning “ActorProjectile”. When the projectile hits a target, it destroys it (DestroyActor).
The problem is, sometimes the destruction of a target occurs while the shooter is still accessing the target (which is a private property of the shooter itself, and updated every 2 seconds via a Timer) in order to rotate towards it.
Tick Event of the “Shooter”
if (Head && target)
{
FRotator newrot = (target->GetActorLocation() - Head->GetComponentLocation()).Rotation();//target can be unaccessible: "The thread tried to read from or write to a virtual address for which it does not have the appropriate access."
Head->SetWorldRotation(newrot);
}
Find Targer, which runs every 2 seconds via Timer
TArray<AActor*> FoundActors;
TArray<AActor*> ActorsInRange;
target = NULL;
UGameplayStatics::GetAllActorsWithTag(GetWorld(), "Enemy", FoundActors);
for (int i = 0; i < FoundActors.Num(); i++)//Get all targets in range
{
if (FVector::Distance(FoundActors[i]->GetActorLocation(), GetActorLocation()) < Range)
{
ActorsInRange.Add(FoundActors[i]);
}
}
if (ActorsInRange.Num() > 0)//Search closest target
{
target = ActorsInRange[0];
for (int i = 0; i < ActorsInRange.Num(); i++)
{
if (FVector::Distance(ActorsInRange[i]->GetActorLocation(), GetActorLocation()) < FVector::Distance(target->GetActorLocation(), GetActorLocation()))
{
target = ActorsInRange[i];
}
}
}
The destruction is called from the projectile itself via BP (I think this can be another problem).
Is there a simple way to fix this ? I thought about IsValid, but what if the pointer becomes “bad” right after I called it ?