Enemy Destroying Powerups

This tutorial will cover enabling the enemy to fire at powerups and destroy them. To start you need to give all of the powerups a tag named “Powerup”. This will allow the enemy lasers to recognize the powerups and destroy them. To set up a new tag select a powerup then in the Inspector in the Tag drop down select Add Tag. That will take you to Tags and Layers. Click the plus icon to create a new tag. Give it the name Powerup. Now go through each of the powerups and assign them the new tag.

Next, go to the Powerup script. Create a new function called PowerupDestroy. Destroy the gameObject in it. This will be used to destroy the powerup from the Laser script.

Now go to the Laser script. In the OnTriggerEnter2D function add another if statement to check if the the other collider has a tag of powerup. Get the Powerup component and call the PowerupDestroy function and destroy the laser gameObject.

The last step is to check if a powerup is in front of the enemy. First add a variable to limit how often the enemy can fire at a powerup just like the enemy is limited in how often it can fire.

Next, in the Update function add an if statement to check if it can fire at a powerup. If it can call the function CheckForPowerups. You will make this function next.

Last, create the CheckForPowerups function. The first part of the function uses Physics2D.OverlapBox. That function will check in a box for a colliders it touches. It will return a collider it hits. The three variables you pass to it are the center of the box which you want out in front of the enemy and the next is a vector to one of the corners of the box, the last is the angle which can be set to 0. You then check if a collider is returned and check if it has a Powerup tag. If it does fire the laser and update when it can next fire at a powerup.

That will allow the enemies to fire at the Powerups and destroy them!