(C++) Safe Array Iteration

This isn’t Unreal-specific, technically, but I’m trying to keep things on the safe side:

I’ve finished the Battery Collector tutorial, and now I’m trying to improve the spawn volume by allowing it to choose from an array of pickups.

As a test, I tried doing this:

// Spawn the pickup
SpawnDelay = FMath::FRandRange(SpawnDelayRangeLow, SpawnDelayRangeHigh);
APickup* const SpawnedPickup = GetWorld()->SpawnActor(WhatElseToSpawn[SpawnDelay], SpawnLocation, SpawnRotation, SpawnParams);

Now, that works (it spawns both Battery_BP and Pickup_BP), and , but I’m not sure it’s safe to iterate over an array like that. Am I risking a crash or error by just picking an item at random? Should I be iterating over the array in a more ‘traditional’ manner?

Thanks in advance!

Okay, I actually figured this out by looking at an old hobby project.

For those that are interested, here’s how I did it:

First, define an array in SpawnVolume.h (I called mine ‘WhatElseToSpawn’, since ‘WhatToSpawn’ was already taken and I didn’t want to break things).

UPROPERTY(EditAnywhere, Category = "Spawning")
TArray <TSubclassOf<class APickup>> WhatElseToSpawn;

Next, in SpawnVolume.cpp, right at the top of the SpawnPickup function, change ‘if WhatToSpawn != 0’ to:

// If we have set something to spawn
for (int32 Index = 0; Index != WhatElseToSpawn.Num(); ++Index)
	if (WhatElseToSpawn[Index] != NULL)
{

(I’m not sure it’s strictly necessary to do this, but it ensures that the array has been populated with at least one pickup).

Finally, go to the bottom of SPawnPickup(), redirect the spawner to look at the array instead of the list:

// Spawn the pickup
APickup* const SpawnedPickup = GetWorld()->SpawnActor<APickup>(WhatElseToSpawn[Index], SpawnLocation, SpawnRotation, SpawnParams);

Note that you do not need to designate how many of an item to spawn; the spawn timer will run the function continuously and do just that.