- Home /
Stop buildings from spawning inside eachother
Hi, I have a really simple game world and I am trying to spawn a range of building prefabs in a random position and rotation. They do that okay, but they will sometimes spawn inside each other and because of the rigidbodies and colliders they tend to explode. So I think I need something that checks where the prefabs are going to be spawned and makes sure that none of the colliders would cross over, but if they do try spawning the prefab in a different position.
public GameObject[] WorldObjects;
public int amountToSpawn;
public Vector3 spawnValues;
void Start()
{
GenerateWorldPrefab();
}
public void GenerateWorldPrefab()
{
for (int i = 0; i < amountToSpawn; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x, spawnValues.x), spawnValues.y, Random.Range(-spawnValues.z, spawnValues.z));
Quaternion spawnRotation = new Quaternion(0, Random.Range(0, 360), 0, 90);
int r = Random.Range(0, WorldObjects.Length);
Instantiate(WorldObjects[r], spawnPosition, spawnRotation);
}
}
This is what I have so far. Any help or suggestions would be great, thanks.
Answer by SkaredCreations · Dec 16, 2014 at 11:46 AM
Use OverlapSphere and Instantiate only if the tag or layer or component of your "buildings" is not existing in the list returned by it, you may want to enclose the whole "for" body inside a while loop so that it'll keep trying to get a position until it can Instantiate (it would be better to have it in a coroutine so that you can have yield return null
after each loop cycle to avoid CPU overhead).