- Home /
Physics.OverlapSphere - do an action only if there are no other gameobjects with tagX around
Hello there!
I try to cast a sphere around a hit.point and identify, whether there are already other objects within that sphere with a specific tag (XMark). If not, an object should be spawned. Does Physics.OverlapSphere maybe not work if instantiated objects? Or am i getting it wrong? From what i find on the internet this should work :-/ Maybe anyone of you can give me a hint how i can do it right?
Thanks a million!
Here is the Code:
MarkXPosition = hit.point;
// Physics.OverlapSphere(center, radius);
Collider[] MarkXFindSphere = Physics.OverlapSphere(MarkXPosition, 5f);
Debug.Log("Checking if XMarks exist closeby ");
foreach (Collider Test in MarkXFindSphere)
{
if (Test.gameObject.tag != ("XMark"))
{
Debug.Log("No XMarks found nearby, spawning one");
Instantiate(XMark, MarkXPosition, XMark.transform.rotation);
}
else
{
Debug.Log("An XMark already exists nearby! Not spawning XMark");
}
}
Answer by glatteinfo · Sep 29, 2021 at 08:40 PM
I guess I found a solution: just in case someone has a simular problem I'm posting it here. The code seems to check for all objects without the tag and spawns one Object for each of them. So I helped myself with adding a counter whenever one object was found with the tag the instantiate wouldnt run since the counter isn't 0 anymore.
MarkXPosition = hit.point;
// Physics.OverlapSphere(center, radius);
Collider[] MarkXFindSphere = Physics.OverlapSphere(MarkXPosition, 2f);
Debug.Log("Checking if XMarks exist closeby ");
foreach (Collider Test in MarkXFindSphere)
{
if (Test.gameObject.tag == ("XMark" ))
{
XmarkAmount = XmarkAmount +1;
return;
}
else
{
XmarkAmount = 0;
}
}
if (XmarkAmount == 0)
{
Debug.Log("No XMarks found nearby, spawning one");
Instantiate(XMark, MarkXPosition, XMark.transform.rotation);
}
It seems like the "else XmarkAmount = 0" part shouldn't be there, otherwise if the last object returned isn't an Xmark it will always spawn an xmark
Your answer
![](https://koobas.hobune.stream/wayback/20220613043623im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Spawner control and ending the level 0 Answers
How can I find all objects in scene under tag "Pickup"? 1 Answer
Script finding a none-existing player clone 2 Answers
Cant Find.() Text component in Canvas 2 Answers
Get parent/root objects in scene? 1 Answer