Enemy Shields Unity2D Space Shooter

Thomas Mauro
3 min readJul 12, 2022

--

The main enemy is becoming more and more dynamic. Now some will spawn in with a shield. Their shield can withstand one player's laser hit. This one didn’t end up with a ton of code. I will explain the best I currently can.

— Variables in Enemy.cs

  • [SerializeField] private GameObject _shield;
  • [SerializeField] private bool _isShieldOn;

— Shield code/logic will go into the start method.

  • int (called is “s” to get a random range of enemies to select from to give a shield of (0100)
  • An if/else statement below that
  • if(s = a percentage (I put mine at 70%) _isShieldOn will = true;
  • else the _isShieldOn will = false;
  • Under that, if/else the shield needed to be set active by linking shield with _isShieldOn
  • Then a debug for the Player is NULL!
Logic with start method

That will give the ability for the shields to show up with no function. Just a bit more code logic within the OnTrigger section for the laser. Here’s the deal with mine. I have created a Damage() method. This is where I will have to place this logic. If you just have the OnTrigger method still then it needs to be in there. I will give an example of both. I found the perfect example from an amazing programmer named Jack Leavey.

This is mine and how I must place the code to activate the shields due to having my Damage() Method etc.
This is the example from Jack Leavey

Alright, now it's time to jump into the Unity editor to finish it off.

  • Dragged the shield prefab into the hierarchy and unpacked the prefab
  • Renamed it EnemyShields
  • Changed the color to a greenish color
  • Dragged the Enemy prefab into the hierarchy
  • Dragged the EnemyShields onto the Enemy prefab
  • Set the shield to off
  • Dragged the EnemyShield prefab from the Enemy in the hierarchy into the Enemy.cs game object slot in the inspector.
  • Updated Override. After that, it was clearly working.
  • Deleted Enemy from the hierarchy

I was thinking I had this wrong because it would not work. Guess what I did! I dragged the EnemShield prefab from the projects folder into the Enemy inspector. You need to drag the one in that is on the Enemy itself.

You can see it working like a charm here. My next article will be about how they are able to dodge that laser now.

--

--