How to not have objects spawn inside each other (C #)

I have multiple objects spawning randomly in my game, but sometimes they spawn inside of each other. I would very much like to know how to make it not happen.

Here is one of my object spawning functions, all of the others are very similar.

void RockSpawn() {
		rockx = UnityEngine.Random.Range(player.transform.position.x - 500, player.transform.position.x - 1000);
		int rockzIndex = UnityEngine.Random.Range (0, rockz.Count);
		Vector3 positionr = new Vector3(rockx, 1, rockz[rockzIndex]);
		GameObject[] rocks = GameObject.FindGameObjectsWithTag("Rock");
		for(int r = 0; r < numberOfObjects; r++) {
			if(rocks.Length < 10) {
				GameObject ro = (GameObject)Instantiate(rock);
				ro.transform.position = positionr;
			}
		}
		
			foreach(GameObject rok in rocks) {
				if(player.transform.position.x + 60 < rok.transform.position.x) {
					Destroy(rok.gameObject);
			}
		}
	}

You would need to check the spawn area for other objects and only spawn if it is clear. If your objects have colliders on them you can use Physics.CheckSphere to check the spawn area.

1 Like

To add to what Gibbonator said, you’ll want to check specifically that there are no other ‘rocks’ in the spawn location.
The collision sphere may detect other objects that could prevent a rock from spawning.

You can do this by checking the tag of each item returned in the collision sphere’s radius, and if there is a rock detected, don’t spawn.
Make sure to tag your rock prefab as a rock though.

Thanks, that worked. :slight_smile:

sorry to hijack this, but is there anyway of doing something similar with rectangle shapes?

same setup having multiple cubes spawn random across a space, but in there i need a walkway to be clear of object… but the capsule or sphere check destroy to much…

Simply add a box collider to your object and check if any of the objects in the collision array matches your check.

k so if i understand it right, you use a spherecheck to catch objects and then check, for example their position, if it lays inside the box collider bounds?