# Doing object movement in a loop in unity

I have a Game Object at position (0, 0, 0). To move it to position (2, 2, 2), I'm using this code below -

void Update () {

Vector3 TargetPosition = new Vector3(2, 2, 2);

transform.position = Vector3.MoveTowards(transform.position,TargetPosition,

23 * Time.deltaTime);

}


How do I put this movement in a loop like behavior so that whenever the Game Object reaches position (2, 2, 2), it again starts moving from (0, 0, 0) to (2, 2, 2) ?

I'm assuming you're a beginner so I've kept this as simple as I could think of. Please let me know if you need more clarity.

public class ObjectMover : MonoBehaviour
{
public Vector3 position1 = new Vector3(0.0f, 0.0f, 0.0f);
public Vector3 position2 = new Vector3(2.0f, 2.0f, 2.0f);

Vector3 currentTargetDestination;

public float distanceTolerance = 0.5f; //you can change the tolerance to whatever you need it to be

void Start()
{
transform.position = position1; //set the initial position
currentTargetDestination = position2;
}

void Update()
{
transform.position = Vector3.MoveTowards(transform.position, currentTargetDestination, 23 * Time.deltaTime);

if(Vector3.Distance(transform.position,currentTargetDestination) <= distanceTolerance)
{
//once we reach the current destination, set the other location as our new destination
if(currentTargetDestination == position1)
{
currentTargetDestination = position2;
}
else
{
currentTargetDestination = position1;
}
}
}
}


I'm not on a machine that has Unity on it, and thus can't test it, but I think that should work (let me know if you see any errors!)

• This code has no errors. But what it does is goes from point (0, 0, 0) to (2, 2, 2) and after that back from (2, 2, 2) to (0, 0, 0) and so on. The movement is reversed. Let me try if I can correct it. Apr 8 '15 at 10:51
• I did some more reading and did it this way. Its in the answer below. Apr 8 '15 at 12:21

I did some more reading. And did it this way. It finally works.

public Vector3 position1 = new Vector3(0 ,0, 0);
public Vector3 position2 = new Vector3(2, 2, 2);

void Update(){

transform.position = Vector3.MoveTowards(transform.position,
position2, 23 * Time.deltaTime);

if (transform.position.x == 2) {

transform.position = position1;

transform.position = Vector3.MoveTowards(transform.position,
position2, 23 * Time.deltaTime);

}

}