I outlined how to create a modular power-up system that will improve any game’s gameplay in my previous article. Let’s tidy up that code with a Switch statement and then introduce an Array to help instantiate the Power-Up GameObjects.
Clean up the code with a Switch
Initially, the Modular Power-up system used an if statements that can become inefficient if they get too big.
Let me introduce you to the Switch Statement that is a much more efficient way to compare a single variable against a series of constants.
In the above example, the variable _powerUpId is checked against each case that will result in the proper method in the Player script to be activated. You must add the break command after the action to exit the switch.
Instantiating a Random Power-up
Working within our SpawnManager script, we need a way to determine which power-up to be instantiated. Let’s assign the power-up GameObject to a variable to use it effectively with an Array.
An Array allows the programmer to use a single variable to store multiple objects.
[SerializeField]
private GameObject[] _powerUps;
Returning to Unity, select the SpawnManager GameObject, and within the Inspector, nominate the number of elements in the array. Expand the Power-Ups item, then drag and drop the Power-up Prefab into the associated Element.
Return to the SpawnManager script and create an IEnumerator method to Instantiate the Power-Ups randomly.
IEnumerator SpawnPowerUpRoutine()
{
while (_stopSpawning == false)
{
int randomPowerUp = Random.Range(0, 2);
Instantiate(_powerUps[randomPowerUp], new Vector3(Random.Range(-2.3f, 2.3f), 8, 0), Quaternion.identity);
yield return new WaitForSeconds(Random.Range(3, 10));
}
}
Lastly, we need to start the Coroutine in the Start method of the SpawnManager script.
StartCoroutine(SpawnPowerUpRoutine());
Here is the complete SpawnManager Script
I hope this article helps you use Switches and arrays.