Avoiding Instantiation within Objects

I was wondering how I could go about avoiding instantiating objects within other objects in the game. For instance, if I randomly spawn 10 cubes on the player’s screen, chances are some of them will overlap.

For future reference, Physics.OverlapSphere is what I ended up using.

            //Randomize spawn location
			float x = Random.Range(-5f, 5f);
			float y = Random.Range(-4f, 4f);
			Vector3 spawnLocation =  new Vector3( x, y, 1f );
			
			//Detect Overlap
			Collider[] hitColliders = Physics.OverlapSphere(spawnLocation, 1.33f);
			
			if(hitColliders.Length == 0)
			{
            }

You could use the objects’ bounding boxes to determine a minimum distance. For example, suppose you have two objects, Obj1 and Obj2. They each have bounding boxes BB1 and BB2. A bounding box has a property called extents which is a vector from the box’s center to a corner.

The minimum distance between Obj1 and Obj2 which ensures no graphical overlap is BB1.extents.magnitude+BB2.extents.magnitude. If you ensure that the distance between the two objects is always equal to or greater than that, then they won’t graphically overlap. The distance would be something like Vector3.Distance(Obj1.transform.position, Obj2.transform.position).

All code in the above is in pseudo-code format, but uses the correct method names you need to look into.

Edit: Note that this will only work robustly if the origins of the objects’ respective local coordinate systems are located at the center of the object. In other words, in local coords, (0,0,0) is inside the center of the object. All Unity primitives obey that requirement, but various custom models might not.