In today's article, we will add a shield to an enemy at random. This system is quite simple but can cause a headache which I will explain at the end.
First, in the ‘Enemy’ script, we will be adding some variables.
In ‘Start’ we will be setting the bool to false, and making sure the game object isn’t active on start. We will also call a ShieldCheck function that we will write real soon.
We’re going to create a pair of functions and a coroutine then apply this to our OnTriggerEnter2D event.
The functions should be self-explanatory. We’re setting the shield power and shields to active in the ‘ShieldIsActive’ function. The ‘ShieldCheck’ is to randomly select an enemy to place the shield on. The coroutine will set the bool to false after a second after the laser collides with the shield.
The collision with the lasers changed a little. Basically, I created a new collision statement for when shields are active that subtracted the shield power and turned off shields. The original code for the laser collision is still there, I just add an ‘And’ to the if statement checking if ‘_isShieldsActive’ is equal to false.
Now, you will need to make sure in Unity that you do a couple of things first before all this will work. You will need to put a shield on all your enemy prefabs and deactivate them. You will also need to edit the box collider on the shields, and possibly change the position at which your lasers spawn from the enemy. I encountered an issue where my shield would appear then disappear right after. I finally noticed that the enemy lasers were colliding with the shield right away, turning it off. That is what I meant by this system can be a headache.