Making an enemy destroy a powerup made for the player in Unity

Samarth Dhroov
2 min readJun 12, 2021

The exercise here demonstrates a way to make the enemy prefab destroy a powerup made for the player.

The plan to make this work is as followed.

  • Identify if the prefab in front of the enemy is for the player.
  • Initiate the fire method as soon as identification is completed.
  • If the powerup of any sort gets hit by the enemy’s laser, it should destroy itself.
  • In order for the identification to work seamlessly, the prefabs can be tagged with a preferred name.
Unity
  • The next thing to check is whether the prefab is in front of the enemy. Since this is a 2D project, the front would be measured on the Y-axis. (The axes can be different depending on the game but since enemies are flowing from top to bottom, mine goes with the Y.)
  • Open the enemy prefab’s script and in its’ OnTriggerMethod( ), introduce the following check.
C#

2.

  • If the enemy successfully enters the if loop above, it must trigger the fire method.
C#
  • Now, here is a fire method that is triggered by the enemy itself. But with this collision, the need is to trigger it again with a shorter delay so that the flowing powerup can be attacked.
  • The code in the if loop shall be something like this.
C#

3.

  • Again using the tag of the enemy’s associated laser prefab, the powerup collider can check for the last task and destroy itself.
  • In the script attached with the powerups, introduce one more condition in the OnTriggerEnter2D( ) method to implement the requirement.
C#

That should be it.

Thank you very much

--

--