Random Animal Stampeed
1. Create a spawn manager
- In the Hierarchy, create an Empty object called “SpawnManager”
- Create a new script called “SpawnManager”, attach it to the Spawn Manager, and open it
- Declare new public GameObject[ ] animalPrefabs;
- In the Inspector, change the Array size to match your animal count, then assign your animals by dragging them from the Project window into the empty slots Note: Make sure you drag them from the Project window; not the Hierarchy! If you're going to spawn objects, you need to make sure you're using Prefabs, which are stored in the Project window.
2. Spawn an animal if S is pressed
-
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 an array
-
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
-
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
-
Toggle between Perspective and Isometric view in the 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
-
Perspective vs Isometric projections
-
Next Lesson
-
Using collisions to feed our animals!