Instantiate Random Objects in a Line

I’ve been achieving this with switch/case statements, but they seem very inefficient. Surely there is a better way of doing the same thing?
Here’s my code:

``````  var straight : Transform;
var curvePiece : Transform;
var jump : Transform;
var numberOfBlocks = 10;
var pieceNumber = 0;

var lengthOfStraight = 40;
var lengthOfCurve = 40;
var lengthOfJump = 80;
var pieceRotation = Quaternion.identity;
var xchangeIncrease = 10;
var xchange = 0;

function Update () {
if (numberOfBlocks > 0){
pieceNumber = Random.Range (1,4);

var position = Vector3(xchange,0,0);

switch (pieceNumber){
case (1):
xchange += lengthOfStraight;
Instantiate(straight, position, Quaternion.identity);
numberOfBlocks--;
print (xchange);
pieceNumber = Random.Range(1,4);

break;

case (2):
xchange += lengthOfCurve;
Instantiate(curvePiece, position, Quaternion.identity);
numberOfBlocks--;
print (xchange);
break;

case (3):

position = Vector3(xchange+lengthOfJump,0,0);
Instantiate(jump, position, Quaternion.identity);
numberOfBlocks--;
print (xchange);
break;
}
}
}
``````

why are you calling pieceNumber = Random.Range(1,4); in each case and at the start of your if?

Regardless, you’d be better off creating a function and passing the object you want to create eg:

``````function createBlock(blockToCreate, xchangeMod){

xchange += xchangeMod;
Instantiate(blockToCreate, position, Quaternion.identity);
numberOfBlocks--;
print (xchange);
break;

}
``````

For example when calling your function for a straight you would use:

``````createBlock(straight,lengthOfStraight);
``````