Randomize Enemy Shields in Unity

2D Space Shooter — Phase II: Core Programming Challenges

Dennisse Pagán Dávila
3 min readAug 4, 2021

Objective: In the previous article, we took a look at how to add enemies with shields. In this article, we will be building up from that code to randomize the enemies so that some of them have shields while others don’t.

Note: This code is aimed at variations of a same Enemy Object and not different Enemy objects altogether.

Programming the Randomizer

  1. Add global variables to keep track of the shield activation and its randomization.

Note: In the previous article I mentioned that using a bool variable in place of a shield strengh variable would work for a one-hit shield, in this article we are using the aforementioned bool variation. However, if you use the shield strengh variable instead, the same logic in this article can be applied to your code with minor modifications.

2. Set the random values in the Start method. They can be any range of your liking, although bear in mind that the range will affect the spawn rarity.

3. Create a method to set the bool to true and activate the shield renderer which will make the shield visible.

The shield renderer variable was added in the previous article,if you are yet, this should be a global variable with a SerializeField. The SerializeField will create a spot in the Inspector for you to drag and drop the Shield Object into it, with this reference in place, you can make it visible(active) or invisible at your convenience.

4. The following code should be placed before you handle the Enemy Object getting destroyed. In my case, I have a method dedicated to handling the Enemy Death. It’s very important that you place this before the object gets destroyed so that it create invulnerability if the Shield is active. Since my shield is a one-hit shield, meaning it only absorbs one hit before becoming inactive, I also deactivate the visualizer and change the bool value accordingly.

5. Now, back to the Start method, we add the condition for the randomizer to spawn a shield. Whenever the randomizer is set to 3(or any number of your choice within the range), the ActivateShield method will be called and make it so the behavior acts accordingly.

The Result:

As you can see, the Shield will absorb one hit before becoming inactive and leaving the Enemy vulnerable again.

This article is part of a series of Core Programming Challenges from GameDevHQ, In the next challenge article, I will discuss how to manage spawn rarity in Unity!

--

--

Dennisse Pagán Dávila
Dennisse Pagán Dávila

Written by Dennisse Pagán Dávila

Software Engineer that specialize in Game Development. Currently looking for new opportunities. Portfolio: dennissepagan.com

No responses yet