I need to create a part of a script which can find the closest object (with a tag). How would I go about this?
For once, something I can be genuinely helpful with.
//Build the array of gameObjects
var things = GameObject.FindGameObjectsWithTag("Tag goes here");
//Our initial point. Can be set to anything, but this is convenient.
var pos = transform.position;
//Set the closest object and it's distance to sutible blank values
var minDistance = Mathf.Infinity;
var closest : Transform;
//Cycle through our objects
for (var thing in things)
{
//Find how far away it is
var dist = Vector3.Distance(pos, way.transform.position);
//If it's closer than the last closest one, make it the new closest
if(dist < minDistance)
{
closest = way.transform;
minDistance = dist;
}
//Wash, rinse, and repeat
}
//When finished, closest is now the closest object.
return closest; //Or whatever needs to be done with it
Hope it helps.