In my 1GAM space shooter, I spawn a bunch of enemy ships around the level at the start of the game and then hide them until the player gets within a certain distance. The main reason for hiding objects after spawning is because it conserves draw calls. This script is part of my Impulse Framework.

ObjectSpawner.cs

ObjectSpawnerEditor.cs

As with all Editor scripts, this must be in a folder called “Editor”.



How To Use

Setup is very simple. I recommend creating a blank game object called Spawner and attaching the script.

Specify the objects you want to randomly spawn in the ObjectSpawnPrefabs array. Note that they don’t have to be prefabs.

array. Note that they don’t have to be prefabs. Number To Spawn is the number of objects you want to randomly spawn.

is the number of objects you want to randomly spawn. Min Distance Between Spawned Objects is the minimum world space units between each spawned object.

is the minimum world space units between each spawned object. Culling Target is the object culling distance will be compared against. For example, if you want to hide objects until the player gets within a certain distance of them, set the player object as the culling target.

is the object culling distance will be compared against. For example, if you want to hide objects until the player gets within a certain distance of them, set the player object as the culling target. Hide Object Spawned Distance is the distance at which culling will occur.

is the distance at which culling will occur. Update Interval is how often (in seconds) the culling will happen. A lower rate increases performance impact.

Lastly, you’ll notice a Box Collider is added to the object you attach this script to. The size of the Box Collider is the spawn area.

CullObject.cs

Actual object culling is handled by CullObject.cs, which checks if the culling target is within the Sphere Collider’s bounds. When ObjectSpawner spawns an object, it creates a child object called “Culling Sphere” with a sphere collider and the CullObject script attached. When the culling target is not within the bounds of the Culling Sphere’s sphere collider, the spawned object is culled (hidden).

