- Home /
Checking if player is near any certain gameobject
So I am trying to make it so that when my player is near any gameobject with a certain tag it sets a bool to true, How do I do this I have been trying many different ways and have got it to work by going distance = Gameobject.find("Sprite").transform.position then saying if(distance < 1) Boolean = true. But this only works with one gameobject and it is not using tags.
Answer by 767_2 · Sep 22, 2014 at 10:04 AM
with this you can cast everything within a radius
void caster(Vector2 center, float radius) {
Collider2D[] hitColliders = Physics2D.OverlapCircleAll(center, radius);
int i = 0;
while (i < hitColliders.Length) {
if(hitColliders[i].tag=="CertainTag")
{
//do something
}
i++;
}
}
}
Would putting physics2d.overlapcircle in place of physic.overlapsphere work? (I am doing this for a 2d game)
yes just use Vector2 ins$$anonymous$$d of Vector3 in this code
Hey so now I have an error unity cannot implicity convert type unityengine.collider2d to unityengine.collider[]
here the code
void caster(Vector2 center, float radius) { Collider[] hitColliders = Physics2D.OverlapCircle(Playercent, Radius); int i = 0; while (i < hitColliders.Length) { if(hitColliders[i].tag=="ground") { onground = true; } i++; } }
the Playercent and Radius are public variables so that I can change them in the editor.
Yes I have tried that just get the same error, cant implicitly convert unityendine.collider2d to unityengine.collider2d[]
Answer by dmg0600 · Sep 22, 2014 at 10:24 PM
Another approach could be this:
bool CheckCloseToTag(string tag, float minimumDistance)
{
GameObject[] goWithTag = GameObject.FindGameObjectsWithTag(tag);
for (int i = 0; i < goWithTag.Length; ++i)
{
if (Vector3.Distance(transform.position, goWithTag[i].transform.position) <= minimumDistance)
return true;
}
return false;
}
To use it just call the method whenever you want, for example:
void Update()
{
...
yourBoolVariable = CheckCloseToTag("sprite", 10);
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613163521im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Performance issues with GetComponent/gameObject.Find in different functions 1 Answer
No renderer.enabled=false on grouped GameObject 2 Answers
where do i find cloth in unity 5.0.2f1 1 Answer
stop the movement of 3rd person controller temporarily 3 Answers
passing a variable to GameObject.Find 2 Answers