Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I check if an object exists at a specific position in unity C#?

Tags:

c#

unity3d

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.

like image 684
Person Avatar asked Oct 15 '17 17:10

Person


People also ask

How do you check if an object is at a specific position unity?

Just check if the array is empty (or the length is 0) and if it is, nothing is touching it.

How do I locate an object in unity?

Click to select the object in the Hierarchy panel. you can hover your mouse over the Scene view and press the F key on your keyboard. The object should swing into view.

How do I reference a specific GameObject in unity?

Simply attach your script with the public reference to a Game Object in your scene and you'll see the reference in the Inspector window. Then you can drag any other object that matches the type of your public reference, to this reference in the Inspector and you can use it in your script.


1 Answers

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;
    }
}
like image 70
Lauren Hinch Avatar answered Oct 05 '22 16:10

Lauren Hinch