change position

Hi all,
there is a scene contain simple 3d cube, i’m thinking make this cube change its position every 5 seconds between 10 different positions (from position1 to 2 then 2 to 3 then 3 to 4 … then 9 to 10) …,
how can i code that without repeat the code 10 times ?

Here is one way to do it:

var float waitTime = 5;
var positionsArray = new Array(10)
positionsArray[0] = new Vector3(0, 0, 0); //starting position
positionsArray[1] = new Vector3(0, 0, 0); //2nd position
positionsArray[2] = new Vector3(0, 0, 0); //etc.
positionsArray[3] = new Vector3(0, 0, 0);
positionsArray[4] = new Vector3(0, 0, 0);
positionsArray[5] = new Vector3(0, 0, 0);
positionsArray[6] = new Vector3(0, 0, 0);
positionsArray[7] = new Vector3(0, 0, 0);
positionsArray[8] = new Vector3(0, 0, 0);
positionsArray[9] = new Vector3(0, 0, 0); //ending position

function Start(){
    MoveToPostion(0);
}

function MoveToPostion(index : int){
    transform.position = positionsArray[index];
    if(index + 1 < positionsArray.length){
        yield WaitForSeconds(waitTime);
        MoveToPosition(index + 1);
    } 
}

Note: I haven’t tested this, and this, by all means, is not the only way to do this.

iammfa, do you want to cube to jump to the next position or move over time? And are the new points at a fixed distance apart from each other? The reason I ask is that if they’re a fixed distance apart, you can simply add that fixed value to the vector pr vectors that you want moved.

Alternatively, you can set up a simple waypoint system. Create empty game objects, place them where you want them in the scene, then drop them into an array.

var myWaypoints : GameObject [ ];

then translate between them or Lerp between them. There are various waypoint examples here in the forum.

sccrstud92, exact this is what i want … thanks
tool55, thanks for your care but i want the object jump to the next position not move…
generally, thanks for all

I tested the previous code but console gave me the next error:

hi!

MoveToPosition and not MoveToPostion !

ohhh sorry for spelling, i correct the error but it gave me new error:

var float waitTime = 5;
var positionsArray = new Array(10)
positionsArray[0] = new Vector3(0, 0, 0); //starting position
positionsArray[1] = new Vector3(0, 0, 0); //2nd position
positionsArray[2] = new Vector3(0, 0, 0); //etc.
positionsArray[3] = new Vector3(0, 0, 0);
positionsArray[4] = new Vector3(0, 0, 0);
positionsArray[5] = new Vector3(0, 0, 0);
positionsArray[6] = new Vector3(0, 0, 0);
positionsArray[7] = new Vector3(0, 0, 0);
positionsArray[8] = new Vector3(0, 0, 0);
positionsArray[9] = new Vector3(0, 0, 0); //ending position

function Start(){
MoveToPosition(0);
}

function MoveToPosition(index : int){
transform.position = positionsArray[index];
if(index + 1 < positionsArray.length){
yield WaitForSeconds(waitTime);
MoveToPosition(positionsArray[index+1]);
}
}