I have this script that randomly generates prefabs within a 2D box collider. However I’ve noticed that sometimes the prefabs spawn into each other. Is there anyway I could prevent this from occurring? I’m not really sure where to start since all of the gameobjects spawn at the same time.
using UnityEngine;
using System.Collections;
public class GeneratePrefabsWithinCollider : MonoBehaviour {
public BoxCollider2D playerCollider;
public GameObject[] placeableObjects;
public GameObject currentObject;
public int numberOfObjects;
public float max;
public void Start () {
for(int i = 0; i < numberOfObjects;i++)
{
for(int j = 0; j < placeableObjects.Length;j++)
{
currentObject = Instantiate(placeableObjects[j],GeneratedPosition(),Quaternion.Euler(0, 0, Random.Range(0f, 360f))) as GameObject;
currentObject.transform.parent = transform;
}
}
}
Vector3 GeneratedPosition()
{
float x,y;
x = UnityEngine.Random.Range(transform.position.x, transform.position.x + max) - GetComponent<Collider2D>().bounds.extents.x;
y = UnityEngine.Random.Range(transform.position.y, transform.position.y + max) - GetComponent<Collider2D>().bounds.extents.y;
return new Vector3(x,y,1);
}
void OnTriggerEnter2D(Collider2D other) {
if(other == playerCollider){
for(int i = 0; i < transform.childCount; i++){
if(transform.GetChild(i).gameObject.activeSelf == false){
transform.GetChild(i).gameObject.SetActive(true);
}
}
}
}
void OnTriggerExit2D(Collider2D other) {
if(other == playerCollider){
for(int i = 0; i < transform.childCount; i++){
if(transform.GetChild(i).gameObject.activeSelf == true){
transform.GetChild(i).gameObject.SetActive(false);
}
}
}
}
}