[JS] Infinite runner script bug that needs smoothing out

Hello,

#pragma strict

var blocks : GameObject[];
var lastBlock : Transform;

var delay : float = 2;

private var num : int;
private var lastNum : int;

InvokeRepeating("Place",0,delay);

function Place()
{
Debug.Log(num);
var block : GameObject;

	while(num == lastNum)
	{
	num = Random.Range(1,5);
	}
	lastNum = num;
	
block = blocks[num];
block.transform.position.z = lastBlock.position.z + 2;
lastBlock = block.transform;
}

Thats my infinite runner script - not amazing, but I am trying to get the basics down before I do anything different. The problem with this script is that sometimes big gaps appear between each separate block – how do I fix this? Thanks.

Currently this is applied to an empty in my scene, with 4 or so blocks at 0,0,0. These blocks are referenced in the array.

I am a sort of advanced beginner, so please explain some complex theories a little dumbed down :slight_smile:

Sorry for bumping my own post, but I’m really struggling with this.

First, arrays are zero-indexed, meaning you need a random number between (0, array.length-1).

You’re choosing a random block. What happens when you have this setup:

[1][2][3][0] (0 is ‘last’ block)

Then ‘3’ is chosen - now you have this setup:

[1][2][0][3]
Big gap between 2 and 0.

You should either instantiate blocks, or only allow blocks to be chosen if they’re already off screen.