# How do I make a waypoint loop function using array? - when it gets to a waypoint, then move to next waypoint

I’ve written this code that works, but i must keep repeating it over and over in script. I feel there must be a way to do this with an array but I’m having a hard time figuring it out.

``````    if (state == 0)
{
float speed = movementSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, waypoint.transform.position, speed);
if (Vector3.Distance(transform.position, waypoint.transform.position) <= 0)
{
state = 1;
}
}
if (state == 1)
{
float speed = movementSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, waypoint1.transform.position, speed);
if (Vector3.Distance(transform.position, waypoint1.transform.position) <= 0)
{
state = 2;
}
}
if (state == 2)
{
``````

etc… (copy paste for eternity)

Here is where i am stuck(my array attempt):

``````        for (int i = 1; i < waypoints.Length; i++)
{
// print(Vector3.Distance(transform.position, waypoints*.transform.position));*
``````

float speed = movementSpeed * Time.deltaTime;
transform.position = Vector3.MoveTowards(transform.position, waypoints*.transform.position, speed);*
if (Vector3.Distance(transform.position, waypoints*.transform.position) < 1)*
{
// break;
}
The problem i have when this runs is that the object just moves to the 1st waypoint and becomes stuck there…

Well you have to repeat for aslong as the object has not arrived to the waypoint.
And you should probably start your array at 0 because arrays are 0 based.

`````` for (int i = 0; i < waypoints.Length; i++)
{
// print(Vector3.Distance(transform.position, waypoints*.transform.position));*
``````

float speed = movementSpeed * Time.deltaTime;
while (Vector3.Distance(transform.position, waypoints*.transform.position) > 1)*
{
transform.position = Vector3.MoveTowards(transform.position,
waypoints*.transform.position, speed);*
}
}