Instantiated object goes for the first waypoint instead of the closest waypoint

hi, i am making a tower defence where when the enemies die, one enemy of lower level take is place, the thing is when the first enemy dies, when the new enemy apears he goes across the map for the first waypoint instead of going for the closest waypoint.

here is the code that makes the enemy apears when one enemy dies:

void die()
{
PlayerStats.money += moneyGain;
GameObject death = (GameObject)Instantiate(deathEffect, transform.position, Quaternion.identity);
Destroy(death, 5f);
waveSpawner.enemiesAlive–;
Destroy(gameObject);

    if(enemyLevel > 1)
    {
        waveSpawner.enemiesAlive++;
       
        GameObject rebirth = (GameObject)Instantiate(newEnemy, transform.position, Quaternion.identity);
       
    }
}

now for the enemy movement here is the code:

[RequireComponent(typeof(enemy))]

public class EnemyMovement : MonoBehaviour {

private Transform target;
private int indexPath = 0;

private enemy enemy;


void Start()
{
    enemy = GetComponent<enemy>();
    target = Waypoints.waypoints[0];
}

void Update()
{
    // calcula a direção  do proximo caminho/waypoint  
    Vector3 dir = target.position - transform.position;
    transform.Translate(dir.normalized * enemy.speed * Time.deltaTime, Space.World);

    if (Vector3.Distance(transform.position, target.position) <= 0.2f)
    {
        nextPath();
    }
    //dá reset ao speed
    enemy.speed = enemy.startSpeed;
}

void nextPath()
{

    if (indexPath >= Waypoints.waypoints.Length - 1)
    {
        endPath();
        return;
    }
    indexPath++;
    target = Waypoints.waypoints[indexPath];
}

void endPath()
{
    PlayerStats.lives--;
    waveSpawner.enemiesAlive--;
    Destroy(gameObject);
}

}

if someone could help me, i would apreciate
sorry for the bad english

Good day.

Did you make the code? If you instantiate a new Object with this eney script, it will comence always be indexPAth=0.

I don’t see anywhere something that changes this… you need the big enemy to store the path he is goint to, and transmit this information to the new little enemy.

Bye

You always set the target to be the first point in the waypoint list at index 0
target = Waypoints.waypoints[0];

What you’ll want to do is to replace that with a FindClosestTarget() function.
in there you’ll want to loop through all of the targets in that array / list
and pick the closest one.

range = (target - transform.position).magnitude;