How do I get a moving object to loop? I've got the object to move back and fourth twice and then it stops completely. It needs to be able to continuously move back and fourth without stopping

using UnityEngine;
using System.Collections;

public class Slider : MonoBehaviour {

public Transform[] target;
public float speed;

private int current;

void Update() 
{
	if (transform.position != target [current].position) 
	{
		Vector3 pos = Vector3.MoveTowards (transform.position, target [current].position, speed * Time.deltaTime);
		GetComponent<Rigidbody> ().MovePosition (pos);
	}
	else current = (current + 1 % target.Length);
		}
	}

C#'s order of operations evaluates % before +. Therefore, current + 1 % target.Length is more like current + (1 % target.Length). Since 1 % anything always equals 1, you’re essentially just incrementing current by 1 each time.

To fix this, change it to (current + 1) % target.Length.

 public Transform[] target;
 public float speed;
 private int current;
 void Update() 
 {
     if (transform.position != target [current].position) 
     {
         Vector3 pos = Vector3.MoveTowards (transform.position, target[current].position, speed * Time.deltaTime);
         GetComponent<Rigidbody> ().MovePosition (pos);
     }
     else
     {
        current = (current + 1) % target.Length;
     }
}

You can extract that code as a method, call it once, then have it call itself recursively.

using UnityEngine; using System.Collections;

public class Slider : MonoBehaviour {

 public Transform[] target;
 public float speed;
 private int current;
 void Start()
 {
      MoveObject();
 }
 
   private void MoveObject()
  {
        if (transform.position != target [current].position) 
       {
           Vector3 pos = Vector3.MoveTowards (transform.position, target[current].position, speed * Time.deltaTime);
           GetComponent<Rigidbody> ().MovePosition (pos);
       }
       else current = (current + 1 % target.Length);

      MoveObject();
   }
}