# An object to follow another object through the waypoint - problem: taking a shortest path instead of walking through the waypoint.

Hello, I have created an object which is moving good along the waypoints. This is the first part. And I have introduced another object. And have calculated the distance between the second object and all other waypoints.

My objective is to move the first object to the waypoints, which are near to the second object. Which is to be done dynamically. And I have taken the waypoints in an array, initially.
My code goes like this:-

``````var waypoint : Transform[];

var dist1 =  Vector3.Distance(waypoint.position,object2.transform.position);
var dist2 =  Vector3.Distance(waypoint.position,object2.transform.position);
var dist3 =  Vector3.Distance(waypoint.position,object2.transform.position);
var dist4 =  Vector3.Distance(waypoint.position,object2.transform.position);
var dist5 =  Vector3.Distance(waypoint.position,object2.transform.position);
var dist6 =  Vector3.Distance(waypoint.position,object2.transform.position);

var minimumDistance = Mathf.Min(dist1,dist2,dist3,dist4,dist5,dist6);
if(minimumDistance==dist1)
{
object1.transform.position = waypoint.position;
object1.animation.Play("walk");
}
if(minimumDistance==dist2)
{
object1.transform.position = waypoint.position;
object1.animation.Play("walk");
}
if(minimumDistance==dist3)
{
girl.transform.position = waypoint.position;
object1.animation.Play("walk");
}
if(minimumDistance==dist4)
{
object1.transform.position = waypoint.position;
object1.animation.Play("walk");
}
if(minimumDistance==dist5)
{
object1.transform.position = waypoint.position;
object1.animation.Play("walk");
}
if(minimumDistance==dist6)
{
object1.transform.position = waypoint.position;
object1.animation.Play("walk");
}
``````

I am sorry. This is trivial, I believe. But I am not able to do animation. But I have mentioned it in the script. But why it isn’t happening, I don’t know. Help! Thanks in advance.

Well, I have no idea how to fix your actual problem, since you haven’t given me enough details, but that code needs to be a lot cleaner.

``````var waypoints : Transform[];

var closestWaypoint : Transform;
var closestDistance : float = 9999999;
for(var waypoint : Transform in waypoints)
{
// Check every waypoint
var curDist : float = Vector3.Distance(waypoint.position, object2.transform.position);
if(curDist < closestDistance)
{
// This is the closet one yet!
closestDistance = curDist;
closestWaypoint = waypoint;
}
}
object1.transform.position = closestWaypoint.position;
object1.animation.Play("walk");
``````

Much nicer! Also, you can use this with any number of waypoints without having to add extra lines.