Reputation: 69
In this case I am looking to full an empty area with an object but I do not want to place an object there if the area is not empty. This is specifically talking about a cube so I am not sure if the checkSphere() works. I am a beginner and I had a lot of trouble finding an answer to this question so although I know it is probably online I had trouble finding something that explained the code in a way I understood and even finding that code.
Upvotes: 5
Views: 20477
Reputation: 330
Try using Physics.OverlapSphere. You can define a sphere at a Vector3 point you'd like to check for ((2, 4, 0) for example). You can give it a low radius (or maybe even 0, but you'd have to check that, I'm not 100% sure if it works).
It returns an array of all colliders that are touching or are inside of the sphere. Just check if the array is empty (or the length is 0) and if it is, nothing is touching it.
You could use it like this:
Collider[] intersecting = Physics.OverlapSphere(new Vector3(2, 4, 0), 0.01f);
if (intersecting.Length == 0) {
//code to run if nothing is intersecting as the length is 0
} else {
//code to run if something is intersecting it
}
or, of course, you could do this:
Collider[] intersecting = Physics.OverlapSphere(new Vector3(2, 4, 0), 0.01);
if (intersecting.Length != 0) {
//code to run if intersecting
}
Hope this helps!
EDIT: Here's a function that just returns true if a point intersects with a collider.
bool isObjectHere(Vector3 position)
{
Collider[] intersecting = Physics.OverlapSphere(position, 0.01f);
if (intersecting.Length == 0)
{
return false;
}
else
{
return true;
}
}
Upvotes: 11
Reputation: 7605
You can try something like this:
First collect all GameObjects in the scene
GameObject[] allObjects = UnityEngine.Object.FindObjectsOfType<GameObject>() ;
Later you can iterate all over those gameObjects to check the distance between their position and your PositionToMatch, which should be a Vector3 with the coordinates you want to check if there is anything there already
foreach(object go in allObjects)
{
float dist = Vector3.Distance(PositionToMatch, go.transform.position);
if(dist <...)
//Here what you need
}
Vector3.Distance will return the distance. You can there set the limit considering the size (radius or diameter) of the of the GameObjects
Upvotes: 0
Reputation: 497
you can use .contains() to check if the object exists and in that case, get the position. I would need to see the code to be more accurate
Upvotes: -1