Download

Spawning actor problems

Hi all, so I’m trying to spawn a random actor from my uclass array but I’ve been struggling to get it to work and the spawnactor just keeps returning null or crashing depending on what I try.
So this is my array:


UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "FloorTiles")
TArray<UClass*> TypesOfTiles;

Then this function gets a random actor:


UClass* AEndlessRunnerGameModeBase::GetRandomTile()
{
int RandomNum = UFunctions::RandomValue(0, TypesOfTiles.Num() - 1);
UClass* RandomTile = TypesOfTiles[RandomNum];

return RandomTile;
}

And this is the function that spawns the actor:


void AEndlessRunnerGameModeBase::SpawnTiles()
{
RandomTileClass = GetRandomTile();

if (RandomTileClass)
{
FActorSpawnParameters SpawnParams;

ATile* NewTile = nullptr;
NewTile = GetWorld()->SpawnActor<ATile>(RandomTileClass->GetClass(), PreviousAttachPointLoc, PreviousAttachPointRot, SpawnParams);
}
}

Any help is much appreciated, thank you :slight_smile:

Could you show the ATile class (post the Tile.h)? I am assuming you have tried



NewTile = GetWorld()->SpawnActor<ATile>(RandomTileClass, PreviousAttachPointLoc, PreviousAttachPointRot, SpawnParams);


I think the problem may be that you are spawning an actor of type ATile from a class of type UClass. Here’s how I usually do it:

Change your array to this:

UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = “FloorTiles”)
TArray<TSubclassOf<ATile>> TypesOfTiles;

And change your GetRandomTile to return TSubclassOf<ATile>

Then change your spawn line to this:
NewTile = GetWorld()->SpawnActor<ATile>(RandomTileClass, PreviousAttachPointLoc, PreviousAttachPointRot, SpawnParams);

Make sure you are initializing your array in your blueprint class.