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

Du Young Yoon
3 min readMay 10, 2021

--

Today, I want to go over two topics:

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

Let’s get started!

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.

Essentially, Switch Statement is pretty similar to our If statement — it would check from the top to bottom for a matching scenario.

  • 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).

Below shows the comparison between If and Switch statement below.

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.

What can Array do?

  • 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[])

Let’s take a look at our example below.

  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.)

Back in SpawnManager script, we can now consolidate our code into 1 coroutine instead of 3 as shown below.

In while loop,

  • 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)

Now, we have randomly spawning PowerUps! Awesome!

Thank you so much for reading!

--

--

Du Young Yoon

XR Unity Developer / Designer / Architect