# GameObject.Find closest ??

How do i find the closest object or an object at a certain distance to that object ?

Give all the objects that you want to check if it’s the closest a tag. You should only have to change the tag of the prefab that you are instantiating from

Then just substitute “tagname” with the tag you chose for those instantiated objects.

``````function Update()
{
print("Closest Object is " + GetClosestObject("tagName").name);
}

function GetClosestObject(tag:String) : GameObject
{
var objectsWithTag = GameObject.FindGameObjectsWithTag(tag);
var closestObject : GameObject;
for (var obj : GameObject in objectsWithTag)
{
if(!closestObject)
{
closestObject = obj;
}
//compares distances
if(Vector3.Distance(transform.position, obj.transform.position) <= Vector3.Distance(transform.position, closestObject.transform.position))
{
closestObject = obj;
}
}
return closestObject;
}
``````

Here is a function that should return the closest gameobject with a collider based on specific distance away from the current object’s position.

``````var radius : float = 50.0;  //this is how far it checks for other objects

function Update()
{
print("Closest Object is " + GetClosestObject().name);
}

function GetClosestObject() : GameObject
{
var colliders : Collider[] = Physics.OverlapSphere (transform.position, radius);
var closestCollider : Collider;
for (var hit : Collider in colliders) {
//checks if it's hitting itself
if(hit.collider == transform.collider)
{
continue;
}
if(!closestCollider)
{
closestCollider = hit;
}
//compares distances
if(Vector3.Distance(transform.position, hit.transform.position) <= Vector3.Distance(transform.position, closestCollider.transform.position))
{
closestCollider = hit;
}
}
return closestCollider.gameObject;
}
``````