How to make looping/generative level segments

I’m trying to make a side-scrolling 2.5d game in which sections of the levels are prefabs, and are triggered just before the player reaches them (so they appear offscreen before you get there). So far the crude manner in which i have got something similar to work is by having an invisible collider/trigger object which the player’s craft hits, when it hits it the game instantiates a prefab level section ahead of the player.

It sort of works, but it is unreliable: the location of the prefab level segment seems to vary with respect to the x axis (the direction the player craft is moving in), and sometimes multiple level segments get instantiated when only 1 should be expected.

So my question is, how would you approach this in a more efficient manner? The idea is to eventually be able to have the level segments selected at random from a selection of different ones, to create an infinite level which isn’t preprogrammed (sort of like templerun). Obviously i ought to be destroying old segments too once they are offscreen.

// instantiates a new level segment on collision.  doesn't seem to work that well though, so different means to do this is required.
	void OnTriggerEnter(Collider other){
		if(other.gameObject.tag == "Player"){
			Debug.Log("Trigger Next Level Segment");
			Rigidbody newLevelSegment = Instantiate(levelsegment, transform.position = new Vector3((transform.position.x + xOffset),yOffset,zOffset), transform.rotation) as Rigidbody;

Hey there,

Lets start off by addressing your smaller issues.

1.) Sometimes multiple instances get instantiated of the level segment.

A.) You need some code to prevent the OnTriggerEnter from firing twice…
bool alreadyTriggered = false;

void OnTriggerEnter(Collider other)
    if(other.gameObject.tag == "Player" && !alreadyTriggered)
        alreadyTriggered = true;
        //Do work here

That is how you prevent a method from running multiple times. If you want it to be able to be triggered multiple times, but not simultaneously, then just set “alreadyTriggered = false;” at the end of the method. This will prevent it from firing if its already running, but when it finishes, it will be able to fire again.

2.) The instantiated location seems to vary

A.) The best method for random level generation is to pick one of the following two options:

Option 1: Set up a grid or path , using empty gameObjects as nodes, and instantiate your next prefab section at the next node in the list. The catch to this is that (if horizontally) you need to make sure all your level segments are the same width.

Option 2: You detect the extents of previous segment, compare it to the extents of the segment you are about to Instantiate, and you get an offset point at which to spawn your level segment. Keep in mind, most object instantiation points, are based on the center of the object. (because in Unity, this is where the pivot point is usually at).