Blow em Up! Destroying the Enemy in Space Shooter with Unity and C#

David Little
3 min readJun 14, 2021

We have a ship. We have lasers. We have enemies to shoot at with those lasers. Now we need things to BLOW UP when they are hit. Enter trigger events.

For this to happen we are going to need for the different prefabs to recognize when they run into each other. This is done through the use of a Rigid Body component which needs to be added to our prefabs.

For this game, lasers can collide with the enemy ships and the enemy ships can collide with the player. So we’re going to add a rigid body to the laser and to the enemy, since they will be the ones doing the action. You choose the Laser and in the Inspector click on ‘Add Component’ and choose ‘Rigidbody’. Ne sure to uncheck Use Gravity since we do not want the laser to fall with any acceleration, in addition to that which is assigned by the _laserSpeed or _enemySpeed variables in the scripts associated with them.

Next set tags for each item in the game, Player as Player, Enemy as Enemy, etc… If a tag does not appear in the tag list create a new tag for what is needed.

We will use these tags to indicate in our scripts which objects will be destroyed. In the Enemy script we’re going to add a block of code that will make these determinations. That code looks like this…

This is telling the Enemy that if it is hit ‘OnTtiggerEnter’ by a Laser that it and the Laser gameObjects are to be destroyed and disappear from view on the display. It is also telling the Enemy that it is destroyed upon contact with the Player gameObject as well but listing it as a separate event.

When you save the script and go back to Unity, you get you player being able to shoot at and destroy the enemy.

Next will be to add lives to the Player and damage upon impact. See you there.

--

--