Project 1: Space Shooter
How to create a modular power up system in Unity
With the help of an array
--
Having multiple power ups causes a problem of how to manage and spawn them. One way of course is to have individual logic for each and everyone, but that would bloat the code and introduce new places where a bug could lie in hiding. So a solution to this is to make a modular system which uses the same code to handle all the power ups and make the power ups themselves be easily distinguishable from one another.
The easiest part is to make the power ups distinguishable, since all it needs is to have an ID with a different number for every power up. This can be achieved by using the field serialization and saving a different ID number for every power up prefab.
The second part is to use that ID to determine what will happen, because all the power ups affect the player then all there is to do is to call different methods of the Player to activate different power ups.
Then comes the spawning part. For this an array works perfectly, that is every power up prefab is stored in the array which then can be used to instantiate them. To make this easier for the developer, present or a future one, the IDs should start from number 0 and continue with increments of one.
Reason for this is, that the index of the first element of the array is 0, then comes 1 and then 2 and so on. Pairing these two together it would mean that the first element, index 0, would have the power up with the ID of 0. Then the second element, index 1, would pair up with the power up that has ID 1, and so on. Doing it this way will guarantee that whatever sort of logic handles the spawning the right power up will spawn.