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.

2 Answers

2

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*.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);
}

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*.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 instead 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*.tag=="ground")* * {* * onground = true;* * }* * i++;* * }* * }* the Playercent and Radius are public variables so that I can change them in the editor.

so change Collider[] to Collider2D[]

Yes I have tried that just get the same error, cant implicitly convert unityendine.collider2d to unityengine.collider2d[]