Journal 43 — Change the Enemy Type in Unity, They Can Now Destroy Your Power Up!

In this challenge, we need to add additional behavior to some of the enemies so they can fire at a power up if they are lined up.

In the Enemy base C# script, we will add reference to a new function to check if the enemy can hit a power up that is in line with it.

Unity C# script for enemy base class, Update method

In this new function, we will do two things: use a Raycast to see if the power up is in line below the enemy, and instantiate a laser prefab to fire at the power up. In the Scene view, we will also use Debug.DrawRay to visualize the ray on each enemy.

Unity C# script for enemy base class, new function to check if enemy can hit power up

In the Powerup C# script, we will also a new check in the OnTrigger function, so that if an enemy laser collides with the power up, it will be destroyed.

Unity C# script for Powerup, destroy power up if OnTrigger with enemy laser

Finally you can see this in action.

Unity Playmode, destroyed ammo power up
Unity Playmode, destroyed shield

Thank you for your time!

An Engineering Manager consultant who is seeking additional skills using Unity 3D for game and application development.