Optimization with Switch Statement & Random Spawning using Array in Unity!

  1. Converting if statement into switch statement for optimization
  2. Spawn 3 PowerUps randomly one at a time by using Array [].

If → Switch Statement

First, let’s take a look at this If statement in PowerUp Script. It’s was great that we could assign numbers to represent PowerUp types, however, it’s getting a bit messy. This is when Switch statement can be very useful.

  • Start with ‘switch(powerUpID)’ with {}.
  • Within {}, each scenario will be represented by a case number followed by : (e.g. case 0:)
  • Under ‘case 0:’ for example, we can write the method that we want to run (e.g. player.TripleShotEnabled())
  • Each case MUST end with ‘break;’.
  • At the end of Switch statement, add ‘default:’ that would run if there is any other scenario (similar to ‘else’ in If statement).

Random Spawning using Array[]

In SpawnManager script, we currently have 3 PowerUps Coroutines set up individually. Since they were written individually, they often times being spawned together or too close to each other. To improve this issue, let’s use Array[] to optimize the script and spawn them one at a time randomly.

  • The array can store multiple elements that are the same data types. It can store a fixed number of elements in a sequence.
  • Arrays are expressed as [] followed by a data type (e.g. int[])
  1. In SpawnManager script, we need to have a variable that can store 3 PowerUps in an array. We did previously create ‘private GameObject _PowerUps;’. We just need to add [] AFTER GameObject.
  2. In SpawnManager’s inspector window, under Power-Ups, it is currently a size 0. Let’s change that to 3.
  3. Now, you should be able to see 3 rows added below. Drag and drop our PowerUp prefabs (*It’s important to put them in order as we will be referring to these numbers to run our code.)
  • Create a variable that will draw a random number between 0 to 3 (representing the array value that we created above).
  • Change the prefab name that we are instantiating as ‘_powerUps[variable]’.
Individually written (LEFT) VS All-in-one (Right)



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Du Young Yoon

Du Young Yoon

XR Unity Developer / Designer / Architect