fbpx
Tower Defense in Unity - Part 3 - Find the Nearest Game Object (Enemy)

Find the Nearest Game Object (Enemy) – Tower Defense Game in Unity – Part 3

Read Time:3 Minute, 6 Second

If you followed the previous guides in this series on building a tower defense game in Unity, you should now have basic enemies and cannons. If you missed the two previous guides in this series, be sure to check them out before we learn how to find the nearest game object in Unity, which in our case is the enemy.

  1. Tower Defense Game in Unity – Part 1
  2. Tower Defense Game in Unity – Part 2

In a tower defense game, there are multiple types of defenses. Each has a different AOE (Area of Effect), range, attack power, attack speed, etc. In this guide, we will make the cannon we already built and programmed to shoot the nearest enemy in range.

Find the Nearest Game Object (Enemy)

Let’s start by adding a new tag as we did in the last guide. This time, call it “Enemy” and assign it to the Enemy prefab.

Add the newly created “Enemy” tag to the Enemy prefab

After that, open the Shoot script, and let’s start edit it.
In the Update method, let’s first find all the enemies in the level.

GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");

Now. let’s being something up. What will happen if we try to find the nearest enemy, but there aren’t any enemies to find? Maybe all the enemies died, maybe we’re in-between waves, or another reason…
If we try to find the nearest enemies but there are no enemies to find, we will get an error and we don’t want it.
Accordingly, all the code we are about to write will be inside the following IF condition right after the above line.

if (enemies.Length > 0)
{

}

In that IF condition, let’s set the closest enemy to the first enemy in the list of enemies we found earlier.

GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
if (enemies.Length > 0)
{
    GameObject closestEnemy = enemies[0];
}

Now we need to iterate over the enemy game objects and check if the current enemy we are checking is closer than the enemy we decided is the closest this far. To do that, we can use the method Distance provided by the Vector3 class.

GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
if (enemies.Length > 0)
{
    GameObject closestEnemy = enemies[0];
    foreach (GameObject enemy in enemies)
    {
        if (Vector3.Distance(enemy.transform.position, transform.position) < Vector3.Distance(closestEnemy.transform.position, transform.position))
        {
            closestEnemy = enemy;
        }
    }
}

Nice, now all we need to do, after finding the closest enemy is to tell our cannon to look at it. We can do that with the LookAt method.

GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
if (enemies.Length > 0)
{
    GameObject closestEnemy = enemies[0];
    foreach (GameObject enemy in enemies)
    {
        if (Vector3.Distance(enemy.transform.position, transform.position) < Vector3.Distance(closestEnemy.transform.position, transform.position))
        {
            closestEnemy = enemy;
        }
    }
    transform.LookAt(closestEnemy.transform.position);
}

So now, your Update method should look like this:

void Update()
{
    GameObject[] enemies = GameObject.FindGameObjectsWithTag("Enemy");
    if (enemies.Length > 0)
    {
        GameObject closestEnemy = enemies[0];
        foreach (GameObject enemy in enemies)
        {
            if (Vector3.Distance(enemy.transform.position, transform.position) < Vector3.Distance(closestEnemy.transform.position, transform.position))
            {
                closestEnemy = enemy;
            }
        }
        transform.LookAt(closestEnemy.transform.position);
    }
    if (Time.time > lastShot + shootInterval)
    {
        lastShot = Time.time;
        Transform spawnTransform = cannonballSpawnLocation.transform;
        Instantiate(cannonballSpawnPrefab, spawnTransform.position, spawnTransform.rotation);
    }
}

Save the script and hit play. Awesome! now our cannon is always aiming at the closest enemy.

What’s Next for our Tower Defense Game

In the following guides in the series of Tower Defense Game in Unity, we will create our first real wave of enemies, make them follow a predefined path, and create another type of cannon and another type of enemy.

Let me know in the comments below if you like this series of guides and would like me to upload the rest of the series.

Leave a Reply

Your email address will not be published. Required fields are marked *