Can someone help me find the closest waypoint to a player?

Right now I’m trying to create a script that tells an enemy, when it spawns, the closest waypoint to the player.

var startPlayerLoc : Vector3;
var player : GameObject;
var waypoints : Array;
var otherEnemies : Array;
function Start () 
{
	player = GameObject.FindGameObjectWithTag("player");
	waypoints = GameObject.FindGameObjectsWithTag("waypoint");
	otherEnemies = GameObject.FindGameObjectsWithTag("enemy");
	startPlayerLoc = findNearest().transform.position;
}

function Update () 
{
	otherEnemies = GameObject.FindGameObjectsWithTag("enemy");
	startPlayerLoc = findNearest().transform.position;
}
function findNearest() : GameObject
{
	waypoints = GameObject.FindGameObjectsWithTag("waypoint");
	var j : int;
	var smallest = Vector3.Distance(player.transform.position, waypoints[0].transform.position);
	for(var i = 1; i < waypoints.length; i++)
	{
		if((Vector3.Distance(player.transform.position, waypoints*.transform.position) < smallest))*
  •  {*
    
  •  	j = i;*
    
  •  }*
    
  • }*
  • return waypoints[j];*
    }
    I don’t get any syntax errors but the enemy has the wrong waypoints assigned to it even when the player is standing right next to a waypoint.
    Thank you for helping me

1 Answer

1

You need to update smallest as well as the index to the point:

for(var i = 1; i < waypoints.length; i++)
{
   var dist = Vector3.Distance(player.transform.position, waypoints*.transform.position);*

if(dist < smallest))
{
smallest = dist;
j = i;
}
}

Thanks it worked!