Unity — Enemy destroying powerups

Benjamin Calvin
2 min readDec 31, 2021

--

Objective: Allow the enemy to destroy a player powerup that appears in front of the enemy.

Starting with the PowerUp script, adding to the existing OnTriggerEnter2D method.

Created a serialized field for the explosion. Destroyed the enemy laser, the powerup, and the collider to ensure nothing interacts with the player beyond the mental shock of the powerup being destroyed.

Ensure all positive pickups are tagged with Powerup. I do not want the enemy destroying something that would give the enemy the advantage.

Side thought on serialized fields:

Handling it through a serialized field in every single powerup is fine with a small game like this. Fair assessment, after 15, 20, 30, 60 powerups, this would not work.

A VFX gameobject could be made like AudioManager and assigning child items like an explosion to it. Then through code, called the same way AudioManager child items are called. All objects would be coded for the explosion and to instantiate it without having to assign a bunch of serialized fields through Unity.

Moving onto the Enemy script:

Enemy laser is already created and assigned.

  • Created a _firelaser bool to control the instantiation of the laser prefab.
  • Called the DestroyPowerup() method in Update. Need a consistent update on if there is an item there
  • Within the void DestroyPowerup method:
  • powerupobj takes care of finding all powerups on the screen
  • if a powerup is found, subtract the distance from the enemy and powerup
  • if the x position of the powerup relative to the enemy is less than 1.0, fire laser once, as the _fireLaser by default is true.

Each laser enemy spawned is given one chance to destroy the player powerup.

--

--

Benjamin Calvin

Dedicated and motivated individual learning programming and sharing my discoveries with you.