Targetting between 2 nearest enemies

Hello.
I wanna write a script allowing me to select between 2 nearest enemies. I made it selecting only 1 the nearest enemy but can’t figure how to realize my final plan.

    private void TargetEnemy()
    {
        foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
        {
            if (selectedTarget == null || Vector3.Distance(player.position, enemy.transform.position) < Vector3.Distance(player.position, selectedTarget.transform.position))
            {
                if (selectedTarget != null)
                {   
                    // Reset highlight
                    selectedTarget.GetComponent<Renderer>().material.color = Color.red;
                }

                selectedTarget = enemy;
                // Highlight
                selectedTarget.GetComponent<Renderer>().material.color = Color.yellow;
            }
        }
    }

It must switch between those 2 game objects not touching the furthest.

I need some help to complete my code please.

It is only getting one because once you set selectedTarget to equal one enemy it is no longer null. Try setting selectedTarget back to null after you change the color to yellow.

That makes no sense. I actually use selectedTarget to deal damage to it.
It’s not getting one, it’s getting the nearest. When I move to others objects they become nearest and I select them.

Hm… did you try making an array of gameobjects then putting all the enemies into that. Then swapping out the end of the first line to check the array of enemies? I don’t care too much for GameObject.Find

NearestTwo Script

using UnityEngine;
using System;
using System.Collections;


public class GenericTest : MonoBehaviour
{
    private GameObject nearestEnemy;
    private GameObject secondEnemy;
    private GameObject selectedTarget;
    private bool targetedNearest;


    private void Awake()
    {
        nearestEnemy = null;
        secondEnemy = null;
        selectedTarget = null;
        targetedNearest = false;  
    }

    private void UpdateNearest(Transform player)
    {
        float nearestDistance = float.MaxValue;
        float secondDistance = float.MaxValue;

        foreach (GameObject enemy in GameObject.FindGameObjectsWithTag("Enemy"))
        {
            float distance = Vector3.Distance(player.position, enemy.transform.position);
            if (nearestDistance > distance)
            {
                nearestDistance = distance;
                nearestEnemy = enemy;
            }
            else if (secondDistance > distance)
            {
                secondDistance = distance;
                secondEnemy = enemy;
            }
        }
    }

    public bool TargetNearest()
    {
        UpdateNearest();
        if (nearestEnemy == null)
            return false;
        SetTarget(nearestEnemy);
        targetedNearest = true;
        return true;
    }

    public bool ToggleTarget()
    {
        UpdateNearest();
        if (targetedNearest)
        {
            if (secondEnemy == null)
                return false;
            SetTarget(secondEnemy);
            targetedNearest = false;
            return true;
        }
        else
        {
            // probably shouldn't ever happen but just in case
            if (nearestEnemy == null)
                return false;
            SetTarget(nearestEnemy);
            targetedNearest = true;
            return true;
        }
    }

    private void SetTarget(GameObject enemy)
    {
        Renderer rend;
        if (selectedTarget != null)
        {
            rend = selectedTarget.GetComponent<Renderer>();
            rend.material.color = Color.red;
        }
        selectedTarget = enemy;
        rend = selectedTarget.GetComponent<Renderer>();
        rend.material.color = Color.yellow;
     
    }
}

The idea behind this code is the user has two keys he can press.
a) Target the nearest enemy. This will always target the nearest enemy no matter what he has targettted
b) Toggle between the two nearest. If he’s on the nearest it will go to the secondnearest. If he’s on the secondnearest it goes to the nearest.

Both of these are public functions some Input manager can call, and will return false if the target didn’t change and true if the target did change

As @unitynoob24 pointed out constantly calling GameObject.FIndxxxx could cause lag in your game if you have a lot of objects and call it a lot. I wrote the code to keep it in line with what you probably already have. Ultimately you might want to refactor it, so some other object is keeping a list of all the enemies in the game, and you just pass that list in as a reference so we don’t have to keep constantly finding them.

1 Like

This is awesome, that’s what I was thinking about but was unsure. Now it’s all clear, thank you.

It works but when I have same distance between 2 objects, it selects only 1 object. That’s odd D:
Nevermind, I’m gonna do something better than that… Switching between all enemies in front of my character! :smile: