After making the Player able to shoot and giving them a cool-down system in previous articles, let’s make some enemies for them to attack.
First, we need to create the Enemy gameobject. Begin with a Cube, rename it to “Enemy” and make it 0.75 on all the Scale values. Next, create a material, name it “Enemy_mat” and apply it to the Enemy gameobject. Then create a new script called “Enemy” and drag it onto the Enemy gameobject. Finally, create a Prefab of the Enemy.
Then in the Enemy script, create a private float named “_speed” with a value of 4, and in the Update method, use transform.Translate to move the Enemy down multiplied by _speed and Time.deltaTime. Under the translate, create an if statement that checks the Enemy’s position on the y axis to see if it is less than -5.5. Inside the if statement, make a local float named “randomX” and equal a random number between the range of -8 and 8. Then create a Vector3 named “spawnPoint” and have it equal a new Vector3 with the values (randomX, 8, 0). Finally, have it set the Enemy’s position to spawnPoint.
Now the Enemy moves down and then resets to the top at a random spot on the x-axis.
Now it is time to create a Tag named “Laser” and set the Laser Prefab’s Tag to it. A Tag is a reference word that you can assign to one or more gameobjects and makes it easy to find and identify the gameobject through code.
In the Enemy script, create an OnTriggerEnter method, then make an if statement that checks if the Collider (other) that entered the Enemy gameobject’s trigger volume has the Tag “Laser”. Inside of the if statement, have it Destroy the other gameobject then itself. You have to Destroy the other gameobject first because if you Destroy the gameobject, the script is on it will not continue the code after that since it was Destroyed.
Now add the Rigidbody component to the Enemy Prefab and disable Use Gravity. Then make sure to enable Is Trigger on the Collider.
With that, the Enemy is now destroyed by the Laser.
In the following article, we will look into having the Enemy damaging the Player.