- Home /
This question was
closed Jun 20, 2019 at 08:30 AM by
ratchetunity for the following reason:
Other
Question by
ratchetunity · Jun 21, 2019 at 09:34 AM ·
instantiatespawnlistsoverlapoverlapsphere
Spawn gameobjects without overlap
Hi!
I'm trying to spawn several gameobjects in an area without overlap. I'm using CheckSphere so they can't overlap and then I save the prefab position on 3 lists (one per axis) so they can't be used again, but it doesn't seem to work. The prefab I'm trying to spawn has a rigidbody and a sphere coliider. This is my code:
[SerializeField] GameObject spherePrefab;
[SerializeField] int numberOfObjects;
private float radiusValue;
List<float> xPositionList = new List<float>();
List<float> yPositionList = new List<float>();
List<float> zPositionList = new List<float>();
private Vector3 spawnPos;
private void Awake()
{
radiusValue = spherePrefab.GetComponent<SphereCollider>().radius * 0.25f;
}
private void Start()
{
for (int i = 0; i < numberOfObjects; i++)
{
Vector3 p;
while (Physics.CheckSphere(spherePrefab.transform.position, radiusValue, 0))
{
p.x = Random.Range(-0.5f, 0.5f);
p.y = Random.Range(-0.5f, 0.5f);
p.z = Random.Range(-0.5f, 0.5f);
spawnPos = transform.TransformPoint(p);
}
while (xPositionList.Contains(spawnPos.x)) spawnPos.x = Random.Range(-0.5f, 0.5f);
while (yPositionList.Contains(spawnPos.y)) spawnPos.y = Random.Range(-0.5f, 0.5f);
while (zPositionList.Contains(spawnPos.z)) spawnPos.z = Random.Range(-0.5f, 0.5f);
Instantiate(spherePrefab, spawnPos, Quaternion.identity, transform);
xPositionList.Add(spawnPos.x);
yPositionList.Add(spawnPos.y);
zPositionList.Add(spawnPos.z);
}
}
Comment