Download

Spawning Actors - Access Violation Reading Location

Hey, I am trying to spawn actors into my scene and my code was working before. But now I am recieiving a Access Violation Reading Location error.

TArray<FSpawnPosition> SpawnPositions = RandomSpawning(MinSpawn, MaxSpawn, Radius, 1.0f, 1.0f);
for (FSpawnPosition Spawn : SpawnPositions)
{
	APawn* Spawned = GetWorld()->SpawnActor<APawn>(ToSpawn);
	Spawned->SetActorRelativeLocation(FVector(0, 0, 500.0f));
	Spawned->AttachToActor(this, FAttachmentTransformRules(EAttachmentRule::KeepRelative, false));
	Spawned->SpawnDefaultController();
	Spawned->Tags.Add(FName("Enemy"));		
}

The debugger says its this line:
Spawned->AttachToActor(this, FAttachmentTransformRules(EAttachmentRule::KeepRelative, false));

I believe the APawn* Spawned is a nullptr, I am able to handle the error by an ensure statement. But now the spawning only works half the time

You can use deferred spawning to set transform properly.

Can you elaborate in that? I’m not sure what you mean? I have am using a debug sphere cast to make sure there are no other objects in the spawn point given.

EDIT: I see you were referring to the C++ function. I fixed my problem by offsetting the Spawn location.

Hi guys,

Deferred spawning give you the opportunity to set variables before spawn your instance inside the world, for example mark an UPROPERTY with meta expose on spawn, but I think is not your case, indeed, apparently your APawn* is nullptr, just verify that with a simple if(Spawned ) before call anything else, your problem is your spawn, World()->SpawnActor<APawn>(APawn::StaticClass(),FTransform, FActorSpawnParameters), this is the most common way, but you have like seven overrides for SpawnActor template method inside UWorld class

The Spawning is failing periodically because of encroaching geometry. If you want to force the actor to spawn regardless of collision, you need to pass the proper parameters into SpawnActor():



	FActorSpawnParameters SpawnParams = FActorSpawnParameters();
	SpawnParams.SpawnCollisionHandlingOverride = ESpawnActorCollisionHandlingMethod::AdjustIfPossibleButAlwaysSpawn;

	GetWorld()->SpawnActor(MyActor, SpawnParams);


There are a few different options for ESpawnActorCollisionHandlingMethod

Deferred Spawning requires the same parameters.

Thanks for the responses everyone, I will try to implement some of this to my code