‘Guided Missiles’ making of Part 2.

Before we can have the player fire a missile, we need a way to set our _closestEnemy variable to the closest enemy. Googling ‘nearest target unity’ and searching through gives us the following code to pilfer:

We can add this method to the MissileBehaviour script as well as adding the below to the Update() method:

Saving the script, jumping back into Unity and deleting any enemies from the hierarchy.

Then if we press play and pause the game before an enemy is spawned and drag a missile prefab into the hierarchy; then un-pause the game the missile will just fly straight up out of the screen. Once an enemy has spawned, we can pause the game and drag a missile in again. Once un-paused, the missile will travel towards the enemy.

Ok, now that we have the missile acting the way we want it too; once instantiated; we need to have the missile instantiate at the player location; preferably; facing the target.

The way this can be accomplished, is to first add another GameObject; which can be called RocketLauncher. Then creating a new script and attaching it to this object. After which we can copy across the GetClosestEnemy() method from our MissileBehaviour script.

Putting the below into the Update() method of our new script:

Saving the script, and jumping back into Unity and clicking play will give:

Now that our Rocket Launcher turns to face the closest enemy, we need to add another method to our RocketLauncherBehaviour script, as below:

Since an _missile object is currently not known to our script, we need to make another variable:

Save the script, jump back into Unity and drag and drop the Missile prefab into this newly created field of the RocketLauncherBehaviour script.

Now, since our player script is where we fire our lasers, it makes sense to add the missile fire command as well. Adding the below to the Update() method of our player script:

Saving the script, and jumping back into Unity and clicking play will give:

We will of course need to increase the time between missiles fired. Using a key other than space would probably be good as well ;). We now also have the same method GetClosestEnemy() on two different scripts, this should be cleaned up. Then we will need to create a power up to pick up the rocket launcher we have just created. These last few things I will leave to you.