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

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

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




XR Unity Developer / Designer / Architect

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

In-depth Java Course: The Ultimate Java Engineering Class

Secure serverless file upload and download on AWS with various Access Control Lists

2D Galaxy Shooter P2: Homing Missiles to the Rescue!

How to convert a React-RoR Web App to PWA, Push Notification using VAPID

Learning to Code: Getting over the Beginners Hump

Hack Cardano! Hosted by CardStarter

Differentiate between DFS and BFS.

Methods of relating

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

More from Medium

Point & Click to Move in Unity

Adding a burst laser powerup

Animating Zombies: Root Transforms

Journal 143 — Unity Project Development, 2.5D Shooter