An efficient approach for deploying multiple powerups in Unity
What if there are more than a dozen powerup effects that could be availed in the game as per the design? It’d be a nightmare to write code separately for each powerup that behaves nearly the same.
Here, the modularity feature of object-oriented programming shall be utilized.
If else statement or switch statements basically steer the execution of the program based on real-time choices. So, let us take a dive into an if-else loop to see how it performs.
The simple implementation is as below.
However, upon the introduction of two more powerups, the first thought to cross a beginner developer’s mind is to write a resembling piece of code and call some relevant methods.
So, instead of player.isTripleShotActive( ) method which begins three bullet firing at a time for 5 seconds, one would write player.IncreaseSpeed( ) or player.WearAShield( ). That seems a lot of repetition.
A little better way to handle it is using an if-else loop.
- Declare a serialized field in the powerup script which is going to be the common component across n number of booster game objects.
- Then, let it compile so that IDs could be assigned in Unity.
- Once these IDs are in place, the code shall take care of the rest.
Here, all one needs to change with implementation is the call to methods.
A little more efficient version will be demonstrated in the next article.
Thank you very much