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

Codility Algorithm Practice Lesson 6: Sorting, Task 3: Triangle — a Python approach

Abstract, Distorted view of Computer Motherboard.

A Practical Guide to start with Kubernetes on GKE

Functional Programming in C

Automating publishing your Flutter apps to Google Play using GitHub Actions

How To Delete Apps From Mac Os

Prevent Reverse Engineering with No-Code Obfuscation

Easy dynamic properties for Java apps

Parameter Passing — Moving multiple File from Blog Storage to Azure SQL DB

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

Tips to Improve Unity Performance

Diverging from Base Enemy Class

Journal 152 — Unity Project Development, 2.5D Shooter

Day 108: Ladder System Part 2