- Home /
This question was
closed Jun 20, 2019 at 11:30 AM by
ratchetunity for the following reason:
Other
Question by
ratchetunity · Jun 12, 2019 at 02:54 PM ·
instantiatepositionrandomoverlapoverlapping
Spawn GameObjects without overlap
Hi! I'm trying to spawn some gameobjects in a chosen area without overlap among them. I save each object position (plus the collider's radius) in 3 lists (one per axis) so the position can not be taken again, but it's not working. This is my code:
[SerializeField] GameObject nodePrefab;
[SerializeField] int numberOfObjects;
[SerializeField] float xValue;
[SerializeField] float yValue;
[SerializeField] float zValue;
private Vector3 spawnPosition;
private float radiusValue;
List<float> xPositionList = new List<float>();
List<float> yPositionList = new List<float>();
List<float> zPositionList = new List<float>();
private void Awake()
{
radiusValue = nodePrefab.GetComponent<SphereCollider>().radius + 0.15f;
}
private void Start () {
for (int i = 0; i < numberOfObjects; i++)
{
float xPos = Random.Range(-xValue, xValue);
float yPos = Random.Range(-yValue, yValue);
float zPos = Random.Range(-zValue, zValue);
while (xPositionList.Contains(xPos)) xPos = Random.Range(-xValue, xValue);
while (yPositionList.Contains(yPos)) yPos = Random.Range(-yValue, yValue);
while (zPositionList.Contains(zPos)) zPos = Random.Range(-zValue, zValue);
spawnPosition = new Vector3(xPos, yPos, zPos);
Instantiate(nodePrefab, spawnPosition, Quaternion.identity, transform);
xPositionList.Add(xPos + radiusValue);
yPositionList.Add(yPos + radiusValue);
zPositionList.Add(zPos + radiusValue);
xPositionList.Add(xPos - radiusValue);
yPositionList.Add(yPos - radiusValue);
zPositionList.Add(zPos - radiusValue);
}
}
Comment
Best Answer
Answer by ernest326648 · Jun 12, 2019 at 06:45 PM
You can use Physics.CheckSphere(position, radius, layermask(optional)) instead of a sphere collider. It works the same way as raycasting. If it collides with another objects it will return a value of true else it will return false. You can also put a layermask on the gameobjects and check if its colliding with another.