title says it all
A simple way to do this is to have an array of all the objects you want to check. Use Vector3.Distance from your position to every single object. Save the first object before you enter the loop in a temporary gameObject. Ignore the first object and loop the rest of the array. Compare the distance of the other objects and the first object. If any object are of lesser distance, replace the object in the temporary gameObject with that object. Once you have finish the loop, the object in the gameObject is closest to you. There might be a more efficient method out there though.
you could also use the squaredistance and multiply the distance you actually want to check with itself, this will save you one square root operation per check.
can you just put the script here, im a newbie…
C# code.
// Variables
public static int MAXNUMOFGAMEOBJECTS = 4; // Maximum number of game objects in the array
public GameObject[] gameObjectArray = new GameObject[MAXNUMOFGAMEOBJECTS]; // Your array to store the game objects
private float temp;
private int posNum; // Position number of that closest object
// Function
GameObject getClosestObject()
{
// Save the position of the first item and the object this script is attached to
temp = Vector3.Distance(gameObjectArray[posNum].transform.position, this.transform.position);
// Loop the array
for (int i = 0; i < MAXNUMOFGAMEOBJECTS; i++)
{
// Don't check yourself
if (posNum != i)
{
// Check if the other object distance is smaller
if (temp > Vector3.Distance(gameObjectArray[i].transform.position, this.transform.position))
{
// If this is true, replace the temp
temp = Vector3.Distance(gameObjectArray[i].transform.position, this.transform.position);
posNum = i;
}
}
}
// Return the gameObject that is closest to the object the script is attached to
return gameObjectArray[posNum];
}
It’s up to you to decide which one goes private and public.
thanks, but, I already figured out what to do hours before you have answer, thank for the help though… thanks again…