4.8.3 Spawn actor from array bug, C++

So basically i’m pretty sure this is a bug because its a very hit and miss with weather it works or not, I’m hoping i’m doing something wrong because i don’t know if you could reproduce this because it requires spamming the function.

but here’s my code:

ACustomPlayerController* PlayerController = Cast<ACustomPlayerController>(GetController());

if (PlayerController->Inventory.IsValidIndex(Value))
{
                    //Here is where it has trouble after aggressive spamming
    		UClass* const Temp = PlayerController->Inventory[Value]->GetClass();
    		UWorld* const World = GetWorld();
    
    		if (Temp)
    		{
    			if (World)
    			{
    				FActorSpawnParameters SpawnParams;
    				SpawnParams.Owner = PlayerController;
    				SpawnParams.Instigator = Instigator;
    				FVector SLoc = FVector(0.f, 0.f, 0.f);
    				FRotator SRot = FRotator(0.f, 0.f, 0.f);
    
    				Spawner = World->SpawnActor<AActor>(Temp, SLoc, SRot, SpawnParams);
    				if (Spawner)
    				{
    					Spawner->AttachRootComponentTo(MyMesh);
    				}
    			}
    	      }
    }

So for some reason it has trouble accessing Inventory[Value] even though i checked to see if if is a valid index,

Extra notes; This is contained in a server rpc function, but it still breaks in offline mode

Hey AndrewM47-

I created a function to try spawning an actor from an array:

void AMyActor::SpawnMyCustomActor()
{

	UWorld* const world = GetWorld();
	FActorSpawnParameters SpawnParams;
	//SpawnParams.Owner = PlayerController;
	SpawnParams.Instigator = Instigator;
	FVector SLoc = FVector(0.f, 0.f, 0.f);
	FRotator SRot = FRotator(0.f, 0.f, 0.f);

	if (GEngine)
	{
		GEngine->AddOnScreenDebugMessage(-1, 4.f, FColor::Red, TEXT("CustomSpawnCalled"));
	}

	for (int32 check = 0; check < TestArray.Num(); check++)
	{
		world->SpawnActor<AActor>(TestArray[check]->GetClass(), SLoc, SRot, SpawnParams);
		if (GEngine)
		{
			GEngine->AddOnScreenDebugMessage(-1, 4.f, FColor::Magenta, FString::FromInt(check));
		}
	}
}

I called this function on tick and found that there were 4 actors (the size of the array) being created every frame as expected. Can you elaborate on exactly what you’re seeing and let me know if this setup works for?

Cheers

I’ve concluded that it isn’t actually to do with my spamming or is it a bug, but its apparently being garbage collected. So i need to find how to stop it from being garbage collected.

The easiest thing to check would be to make sure that your array is a UPROPERTY(). If it is not then this would explain why it’s getting GC’ed.

It is a UPROPERTY, it is also transient and replicated

Ok so i fixed my problem, i realize where i went wrong. I was referencing a copy of the actor so when i destroy the actor it was garbage collecting the copy but i change my TArray to TArray and now it all works well and doesn’t get garbage collected. Thanks to everyone for helping