How to randomly spawn objects in one axis without them touching eaching other?

Hey, so the randomizing part is easy but I couldn’t get the objects (with Colliders) not touch each other while spawning at a new location (imagine background mountains that shuffle and relocate in an endless runner)
I tried to use Bounds.Intersects but failed… please take a look:

Bounds spawnBounds = this.GetComponent<Renderer> ().bounds;

		for(int i=0; i<backgrounds.Length; i++) {
			Transform aBackground = backgrounds *;*
  •  	Transform pBackground;*
    
  •  	if (i == 0) {*
    
  •  		pBackground = aBackground;*
    
  •  	} else {*
    
  •  		pBackground = backgrounds [i - 1];*
    
  •  	}*
    
  •  	if (!aBackground.gameObject.GetComponent <Renderer> ().bounds.Intersects (pBackground.gameObject.GetComponent <Renderer> ().bounds)) {*
    
  •  		aBackground.position = new Vector3 (Random.Range (spawnBounds.min.x, spawnBounds.max.x), aBackground.position.y, aBackground.position.z);*
    
  •  		print ("not intersecting");*
    

} else {

  •  		aBackground.position = new Vector3 (pBackground.gameObject.GetComponent <Renderer>().bounds.max.x+1.0f, aBackground.position.y, aBackground.position.z);*
    
  •  	}*
    

[85698-screen-shot-2017-01-10-at-14536-pm.png|85698]*
the green bounding box belongs to the ‘spawnBounds’ object which the mountain boxes are its children…
Thanks!
*

If every single ‘mountain’ object would have a BoxCollider object inside, and every single object would be inside of a list, you could do this:

  1. Put the random coordinates for the mountain inside variables.

  2. Say, you’re randomizing the size of the box as well. Store the sizes of the extens somewhere as well. (You’d only really need the x axis extents.)

  3. Now, once you’ve placed them all, loop through the list of the background objects that you have and do a check, if the object’s left and right sides are not inside any other object.
    e.g.

You could use Physics.CheckBox, passing in the random position and random extents for the box and if it returns true, it would mean that the new object would intersect it. If so, generate new random position and new random extents, and try it again. If it returns false (as in it doesn’t intersect anything), instantiate the object there.