MiniGame2: Pizza Carnage
This game consists of eliminating waves of aliens by throwing pieces of pizza at them.
You will learn to:
Create a spawner
Use randomness
Create and use Prefabs
Detect collisions
Model a pizza and an alien with their colliders
Scene Layout
Player control
Pizza
Without a doubt, the most interesting part of this project is coming up: modeling a slice of pizza in 3D
Prefab
The player will throw pizza slices to the aliens, so we need to reuse the same slice of pizza multiple times. For this, we transform our 3D pizza slice into a prefab.
Firing pizza
Go back in the player controller script
Add a new variable: public GameObject pizzaSlice
Link this variable to your prefab
![]()
In the update() function, detect when the spacebar is pressed
if ( Input.GetKeyDown(KeyCode.Space) )If we look at the documentation:
We notice a version that is interesting:
First parameter: the prefab we want to instantiate
Its position
Its rotation
Instantiate a prefab when spacebar is pressed
Self-destruction
In order to improve game performance, we need to destroy projectiles when they go out of bounds.
Alien Spawner
Our spawn manager script will be associated to a hidden GameObject:
Right click in the Hierarchy windows and select: Create Empty
Rename this object to spawnmanager
Create a script and attach it to the spawn manager
Edit the script and add an array of prefabs as a public member:
public GameObject[] alienPrefabs;Select the spawnmanager object
In the Inspector window, set the size of the array to 3
Drag and drop the 3 alien prefabs to fill the array
Create a function Spawn() in the Spawnmanager script
Randomly choose the alien prefabs
int randomValue = Random.Range(0, 3); // generate a random integer number between 0 and 2Make the alien appears in front of the player by randomly choosing its location
Call the Spawn() function from the Start() function
Help in case nothing works
void RandomSpawn() { int r = Random.Range(0, 3); Vector3 V = alienPrefabs[r].transform.position; V.z = Random.Range(-6, 6); Instantiate(alienPrefabs[r], V, alienPrefabs[r].transform.rotation); }Enter Play mode:
![]()
Remove the Spawn() function from the Start() function
We now spawn the aliens on a timer
void Start() { float startDelay = 2; float spawnInterval = 3; InvokeRepeating("RandomSpawn", startDelay, spawnInterval); }
Collision
Double click on the pizza prefab
Go back to the scene
Create a new script for aliens and associate this script to each alien prefabs
This script must destroy the alien and also the pizza
Destroy(gameObject); Destroy(other.gameObject);Configure the collision system so that the game works properly
Configure colliders if needed
Select the right function for collision management
Here is the final version of the game: