I have this code here. Sometimes is overlapping on another object. How can I check for empty space before the spawn can happen?

`````` public Transform prefab1;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag ("Pick Up A")) {
Vector3 position = new Vector3 (Random.Range (-9.6f, 9.6f), .5f, Random.Range (-9.6f, 9.6f));
Instantiate (prefab1, position, Quaternion.identity);
}
}
``````

if you push your objects into a list when you spawn them you could check positions for distance before you spawn.

you would then loop though your list to see if it is open… if not choose another and repeat. this script uses a loop inside a loop to get what your asking for

``````	List<Transform> guys;
GameObject g;
int i;
int i2;

public float distance;
Vector3 position;

void Start(){
distance=1.5f;//<distance considered too close
guys = new List<Transform> ();
}
public Transform prefab1;
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag ("Pick Up A")) {

i2=10;//<limit amount of times to search to avoid endless loop

while(i2>0){i2--;
position = new Vector3 (Random.Range (-9.6f, 9.6f), .5f, Random.Range (-9.6f, 9.6f));
i=guys.Count;
while(i>0){i--;
if(Mathf.Abs(position.x-guys_.position.x)>distance&&Mathf.Abs(position.z-guys*.position.z)>distance)*_
``````

* {i=0;i2=0;}*
* }}*
* g=Instantiate (prefab1, position, Quaternion.identity) as GameObject;*
* }*
* }*
make sure to say this at the very top of your script so you can use lists:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;

This method returns true if this collider is overlapping another collider…

``````public bool IsOverlapping()
{
ContactFilter2D  contactFilter = new ContactFilter2D;
Collider2D[] results = Collider2D[1];  //Array length cant be 0

if(GetComponent<Collider2D>().OverlapCollider(contactFilter,results).Equals(0))
{
return false;
} else {
return true;
}
}
``````

Example usage…

``````if(IsOverlapping)
{
GetComponent<SpriteRenderer>().color = Color.red;
}else{
GetComponent<SpriteRenderer>().color = Color.green;
}
``````

This is in 2D, but should work the same for 3D.