Power Up Drop
In this article I will go over how to spawn power ups when an enemy is destroyed.
First, there is a Spawn Manager that is in charge of spawning enemies and power ups. I am converting it so when an enemy is destroyed there is a potential of a power up being dropped. This article will just cover the power ups being dropped when the enemy is destroyed. I will cover adding in a balanced spawning system for the power ups.
The Spawn Manager has an array of game objects that holds the power ups.
Since the spawn manager is holding the power ups I will need access to it from the enemy(ies) script(s). A SpawnManager variable will be created, along with a Vector3 that will hold the position of the enemy when it died.
In the OnStart, we grab the SpawnManger component and assign it to our variable.
In the OnTriggerEnter, this is where the enemy is getting hit by either a projectile or the player we want to grab the current position of the enemy before it is destroyed and assign it to our powerUpSpawnPosition so where know where to have the power up spawn when we instantiate it.
We are going to create a method that will spawn the power and we first check to see if the enemyDead is true and you can see above in the OnTrigger that is set to true after the grab the position. If the enemy is dead we want and local int variable that will pick a number between 0 to 7. This is because we have 7 power ups in our array that we want to grab randomly. Then we will Instantiate the power up by getting the power up array from the spawn manager and pass in the random number that will determine which one will be created and create it at the position of where the enemy was destroyed and just keep the rotation the same using Quaternion and set it to its identity.
Now, you can call this method when the enemy is about to be destroyed to spawn the power up and you want to make sure you call it before you destroy the enemy game object or it will not be created.
Each power up has the sam script attached that contains a movement component in the update, so when it is created it will move down the screen until it gets below the screen and it will be destroyed. That is how you can spawn a power up where an enemy was destroyed.