avoid spawned gameobject overlap

i am making an endless runner where random obstacles are spawned at the right edge of the screen from where they start moving to the left. currently i am using “yield WaitForSeconds” but this gives problems when the objects change movement speed and the gaps between them start getting bigger and bigger.

so i wanted to check collision and if true destroy the latest gameobject spawned, until the last spawned gameobject moves out of the way.

please help

heres the code im using:

var cube1 : Transform;
var cube2 : Transform;

function Start () {
	for (var y = 0; y < 5; y--)
	{
	
	var i = Random.Range(0,10);
	
	if(i <= 5)
	{
	yield WaitForSeconds (0.5);
 	var cube1 = Instantiate(cube1, Vector3(10,-4,0), Quaternion.identity);
 	}
 	
 	if(i > 5)
	{
	yield WaitForSeconds (0.5);
 	var cube2 = Instantiate(cube2, Vector3(10,-4,0), Quaternion.identity);
 	}
 	
 	}
}

thanks…

If you want to destroy the objects that go out of screen, attach this script to them:

function Update(){
    if (renderer.isVisible == false) Destroy(gameObject);
}

isVisible actually means that the object is inside or touching any camera frustum. Once your obstacle completely disappears at the left, isVisible becomes false and the object is destroyed.

You could attach this code to the obstacle prefab, or add it to the object right after it’s created - supposing this script is called “SelfDestruction.js”, you could do something like this:

    ...
    var cube1 = Instantiate(cube1, Vector3(10,-4,0), Quaternion.identity);
    cube1.gameObject.AddComponent(SelfDestruction); // add the script
    ...

Another even simplest alternative would be to define the lifetime of the object when it’s created:

    ...
    var cube1 = Instantiate(cube1, Vector3(10,-4,0), Quaternion.identity);
    Destroy(cube1.gameObject, 10); // object will self-destruct in 10 seconds
    ...