Lesson 2.3 - Random Animal Stampede
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.
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
Spawn random animals from 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
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
Change the perspective of the camera
- Toggle between Perspective and Isometric view in Scene view to appreciate the difference
- Select the camera and change the Projection from “Perspective” to “Orthographic”