- Home /
GameObject.Find closest ??
How do i find the closest object or an object at a certain distance to that object ?
how can i find the closest object with a certain name if there are multiple objects with the same name and that are instantiated when game starts and that doesn't have collider ?
Thanks for reply
Answer by Lttldude · Apr 15, 2012 at 11:31 PM
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;
}
Thanks this finds the closest object but i can't figure how to assign that object to a var like var object : Transform; // and here to be assigned that object
Thanks for reply
Thank you Lttldude for your response, it helped me greatly. However, I've now run into a problem with instantiating objects into the scene. After the code is running and an object has found the closest object tagged ("enemy"), if you instantiate a new object tagged ("enemy") into the scene, the current object loses its closest object and cant regain it. Any idea why?
just a little add: remove : if(!closestObject) { closestObject = obj; }
and use : var closestObject : GameObject= objectsWithTag[0]; I'm not sure of the syntax I use csharp.
Answer by Lttldude · Apr 15, 2012 at 10:10 PM
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;
}