How do I select targets?

 void UpdateTarget()
    {
        GameObject[] enemies = GameObject.FindGameObjectsWithTag("ennemy");
        float shortestDistance = Mathf.Infinity;
        GameObject nearestEnemy = null;



        foreach (GameObject enemy in enemies)
        {
            float distanceToEnemy = Vector3.Distance(transform.position, enemy.transform.position);
            if (distanceToEnemy < shortestDistance)
            {
                shortestDistance = distanceToEnemy;
                nearestEnemy = enemy;
            }
        }
        if (nearestEnemy != null && shortestDistance <= range)
        {
            target = nearestEnemy.transform;
        }
        else
        {
            target = null;
        }

Currently using this to select nearest target but I want to change it so I can scroll through targets using
if (Input.GetKey(KeyCode.JoystickButton5)
(gets next nearest target)

thanks

I would probably just create a ‘List targets’ of targets, ordered by their distance. This allows you to simply save the current targetIndex and increment that when you detect a JoystickButton5 press. Your selected target will then be targets[targetIndex].

It’s up to you if you want to only calculate this list once, or on a button press, or every frame. However, if the targets are dynamic, ie move, recalculating the list may change the currently selected target as well, since the target at the targetIndex can change its position in the list. From what you described you want, this seems like a problem with the idea rather than the implementation tho. If this is unacceptable you may wanna explain what you need this for in more detail so we can tailor a solution to your problem.

Last but not least, it is not recommended to use Find() and any of its variations for anything other than prototyping. It’s never required to use them, and they are slow and become even slower as your project grows since they have to look through all objects.

I’d also go with a list of enemies but Keep it globally. Add enemies when they spawn, and remove them when they die or de-spawn for other reasons. That way you can use that list for other functions like ‘next target’, ‘previous target’, ‘closest target’, ‘closest attacking target’, ‘closest target in front’ etc. It also avoids the costly ‘Find()’ call every time you switch targets. In the same vein, don’t use Distance(), but use magnitudeSqr(target.Position - own.Position) when sorting for distance (although both Points may constiture premature optimization when you only have a few enemies in the Scene).