Random Animal Stampeed
1. Create a spawn manager
If we are going to be doing all of this complex spawning of objects, we should have a dedicated script to manage the process, as well as an object to attach it to.
- In the Hierarchy, create an Empty object called “SpawnManager”
2. Spawn an animal if S is pressed
We’ve created an array and assigned our animals to it, but that doesn’t do much good until we have a way to spawn them during the game. Let’s create a temporary solution for choosing and spawning the animals.
-
In Update(), write an if-then statement to instantiate a new animal prefab at the top of the screen if S is pressed
Declare a new public int animalIndex and incorporate it in the Instantiate call, then test editing the value in the Inspector

3. Spawn random animals from array
We can spawn animals by pressing S, but doing so only spawns an animal at the array index we specify. We need to randomize the selection so that S can spawn a random animal based on the index, without our specification.
-
In the if-statement checking if S is pressed, generate a random int animalIndex between 0 and the length of the array
Remove the global animalIndex variable, since it is only needed locally in the if-statement

4. Randomize the spawn location
We can press S to spawn random animals from animalIndex, but they all pop up in the same place! We need to randomize their spawn position, so they don’t march down the screen in a straight line.
-
Replace the X value for the Vector3 with Random.Range(-20, 20), then test
Within the if-statement, make a new local Vector3 spawnPos variable
At the top of the class, create private float variables for spawnRangeX and spawnPosZ
5.Change the perspective of the camera
Our Spawn Manager is coming along nicely, so let’s take a break and mess with the camera.Changing the camera’s perspective might offer a more appropriate view for this top-down game.
-
Toggle between Perspective and Isometric view in Scene view to appreciate the difference
Select the camera and change the Projection from “Perspective” to “Orthographic”
6. Lesson Recap
-
The player can press the S to spawn an animal
-
Animal selection and spawn location are randomized
Camera projection (perspective/orthographic) selected
New Concepts & Skills
-
-
Spawn Manager
-
Arrays
Keycodes
Random generation
Local vs Global variables
PerspectivePrespective vs Isometric projections
Next Lesson
-
Using collisions to feed our animals!