Physics.OverlapSphere

Hello, guys. I have looking for some examples of using the Physics.OverlapSphere, but nowhere I can’t find good and easy examples. I spent on this about 2 hours, but can’t uderstand how can I use it.

I have a some spawner, that spawn some objects in random time at random position, but sometimes it spawn this objects in same position of obstacles or in hard getting areas. So, I want to make some script that will check if there obstacles(objects) in some area and if they are , it will cancel of spawning objects.

Can someone say, in what way I can do this? If it Physics.OverlapSphere - how must I use it?
:slight_smile:

1 Like

Have you tried the sample code in the doc? Unity - Scripting API: Physics.OverlapSphere

I tried it, but honestly saying I don’t understand how can I use it. I think that I must check if there is some objects in area and if there is something it must return some bool or some value. And when I receive it I know what I need to do, next step is simple for me. I read that it must return some array of objects, so maybe I can use it as " if in array is some object, I will switch off my spawn script.

It returns an array of colliders; I guess you could use that to determine if your area is okay to spawn your objects.

1 Like

If all you want to know is if there’s anything in the sphere, this will do the trick:

Collider[] hitColliders = Physics.OverlapSphere(center, radius);
if (hitColliders.Length != 0)
{
  Debug.Log("Found something!");
}

(Not sure if hitColliders also need a null check; doubt it, but better check to be sure)

1 Like
using UnityEngine;

public class StuffScript : MonoBehaviour
{
    Collider[] hitColliders;

    void ExplosionDamage(Vector3 center, float radius)
    {
        hitColliders = Physics.OverlapSphere(center, radius);
        int i = 10;
        while (i < hitColliders.Length)
        {
            hitColliders[i].SendMessage("AddDamage");
            i++;
        }
    }

    public void Update()
    {
        ExplosionDamage(new Vector3(1,1,1), 5);
        if(hitColliders.Length >= 1)
        {
            //stop my spawn
        }
    }
}

For example I need to make Update in which every frame will call this ExplosionDamage method to check if there some objects in area and then if this array has 1 or more obj. then i will turn off my spawn method?

Guys, look please my “example” script, am I correct understand it?

No, that doesn’t look right :slight_smile:
For one, I can’t imagine you want Explosion Damage in Update.
Secondly, why would the loop start at 10… < array length?
third - I don’t usually see SendMessage recommended.

But why not? Then how this method will start? It’s not in Alive,Start,Update… Or it’s start automatically?
Oh, in loop it’s my mistake, I was test it and write 10 here… I changed it to 0 now :smile:
For what need this SendMessage? It write me the message in console?

Yeah I suppose the doc is a bit weird, when looping could’ve been done like this:

for (int i = 0; i < hitColliders.Length; ++i)
{
  // do something with hitColliders[i]
}

The “SendMessage” part is just an example. It’s up to you to actually do something (or not do something) for each collider. I’m not a super big fan of using SendMessage to call functions since it’s so easy to make typos and end up wondering why your functions aren’t being called.

But, I don’t need looping. I need only when the object, to which attached this script, spawn and then check if there some obstacles in this area. If they are, this object (that was spawned) must be destroyed.

So, is it correct? But, I don’t understand one, how method ExplosionDamage will called? I must call it from another method? Or it starts in start of game?

using UnityEngine;

public class StuffScript : MonoBehaviour
{

    void ExplosionDamage(Vector3 center, float radius)
    {
        Collider[] hitColliders = hitColliders = Physics.OverlapSphere(center, radius);
       
        if (hitColliders.Length > 0)
        {
            //destroy some obj
        }
    }

    public void check()
    {
        ExplosionDamage(new Vector3(0,0,0), 5);
    }
}

Method “check” I will call from another script, which spawns objects.
What will you say about this, guys? :slight_smile:

Guys, I followed your advices and I made the script for spawn stuff.objects which at first I check zone where it must spawn and if it will be correct it will spawn objects. Please, look it and what you say about this? :):):slight_smile:

using UnityEngine;

public class StuffSpawnerScript : MonoBehaviour {

    public float spawnMin;
    public float spawnMax;
    public GameObject[] Stuff;

    Collider[] hitColliders;

    void Start()
    {
        SpawnStuff();
    }

    void SpawnStuff()
    {
        float spawnMin = 2f;
        float spawnMax = 3f;
        float spawnCoor = Random.Range(-4f, 4f);

        CheckArea(new Vector3(15, spawnCoor, -2), 5);

       
        if (hitColliders.Length > 0)
        {
            print("there is object!!!");
        }
        if (hitColliders.Length == 0)
        {
            Instantiate(Stuff[0], new Vector3(15, spawnCoor, -2), Quaternion.identity);
            Invoke("SpawnStuff", Random.Range(spawnMin, spawnMax));
        }
    }


    void CheckArea(Vector3 center, float radius)
    {
        hitColliders = hitColliders = Physics.OverlapSphere(center, radius);
    }
}

I think that could probably work. However, it’s possible that you could simply check the area where you would spawn the object first to see if overlap is there. If it is, don’t spawn your object in the first place, and if it isn’t… then spawn it :slight_smile:
Almost the same thing, except you won’t have to create & destroy potentially, if not needed.

I edited previous message and repaired my if :). and now I will check if it works :slight_smile:

It’s not working. Even none message don’t appear. It feels like it does not check if there is an object in the area.
For reference, my game is 2d and maybe I don’t need to make Vector3? Maybe I need to make Vector2? And my objects on scene has different layers looks like parallel scrolling.

If you just want to tell if a sphere overlaps ANYTHING… it’s better to use CheckSphere:
https://docs.unity3d.com/ScriptReference/Physics.CheckSphere.html

No allocation, it just returns a boolean.

Something like this should accomplish OP’s needs.

using UnityEngine;

public class StuffSpawnerScript : MonoBehaviour {

    public float spawnMin;
    public float spawnMax;
    public GameObject[] Stuff;

    Collider[] hitColliders;

    void Start()
    {
        SpawnStuff();
    }

    void SpawnStuff()
    {
        float spawnMin = 2f;
        float spawnMax = 3f;
        float spawnCoor = Random.Range(-4f, 4f);
       
        var pos = new Vector3(15f, spawnCoor, -2f);
        if (Physics.CheckSphere(pos, 5))
        {
            print("there is object!!!");
        }
        else
        {
            Instantiate(Stuff[0], pos, Quaternion.identity);
            Invoke("SpawnStuff", Random.Range(spawnMin, spawnMax));
        }
    }
}
using UnityEngine;

public class StuffSpawnerScript : MonoBehaviour {

    public float spawnMin;
    public float spawnMax;
    public GameObject[] Stuff;

    Collider[] hitColliders;

    void Start()
    {
        SpawnStuff();
    }

    void SpawnStuff()
    {
        float spawnMin = 2f;
        float spawnMax = 3f;
        float spawnCoor = Random.Range(-4f, 4f);

        var pos = new Vector3(15f, spawnCoor, 0);
        if (Physics.CheckSphere(pos, 50))
        {
            print("there is object!!!");
        }
        else
        {
            Instantiate(Stuff[0], pos, Quaternion.identity);
            Invoke("SpawnStuff", Random.Range(spawnMin, spawnMax));
        }
    }
}

I tried it now, but it still do nothing, even none messages.
As I wrote before: For reference, my game is 2d and maybe I don’t need to make Vector3? Maybe I need to make Vector2? And my objects on scene has different layers looks like parallel scrolling.

your game is 2D?

Are you using 2D colliders?

Yeah… Physics is for the 3d physics system (PhysX)… there’s a different API for the 2d physics system (Box2D):

2 Likes

Must have missed the part about 2d.
Maybe try: Unity - Scripting API: Physics2D.OverlapCircle
or : Unity - Scripting API: Physics2D.OverlapCircleNonAlloc

Err, and as @lordofduct said: make sure you’re using 2d colliders, of course :slight_smile:

2 Likes

It’s unfortunate that Physics2D doesn’t have a ‘check’ method.

Personally I’d use the OverlapCircle that returns 1 object and test != null.

using UnityEngine;

public class StuffSpawnerScript : MonoBehaviour {

    public float spawnMin;
    public float spawnMax;
    public GameObject[] Stuff;

    Collider[] hitColliders;

    void Start()
    {
        SpawnStuff();
    }

    void SpawnStuff()
    {
        float spawnMin = 2f;
        float spawnMax = 3f;
        float spawnCoor = Random.Range(-4f, 4f);

        if (Physics.OverlapCircle(new Vector2(15f, spawnCoor), 50) != null)
        {
            print("there is object!!!");
        }
        else
        {
            Instantiate(Stuff[0], new Vector3(15f, spawnCoor, 0), Quaternion.identity);
            Invoke("SpawnStuff", Random.Range(spawnMin, spawnMax));
        }
    }
}
1 Like