Get nearest gameObject from small group


I'm trying to create a script which finds the nearest gameObject to the player. The search should only take place on gameObjects of a certain type, and I was wondering what the most efficient way to do this. If you imagine a game of football, where there are 11 players on your side, I need some logic which would check which of the 11 "Teammate" gameObjects is closest in order to pass the ball.

My immediate solution would be to store all the gameObjects I want to 'search' in an array, then iterate through that array to find the nearest.

Is there a quicker, more efficient way of doing this?

Yes your solution is pretty much correct. One such implementation might look like this, assuming your "Player" script is attached to every player gameObject and the 'team' is selected as a variable on the player script:

(only relevant parts of the class shown, the rest of your player code would be in this class too)

using UnityEngine;
using System.Collections.Generic;

public class Player : MonoBehaviour {

    public enum Team { Reds, Blues }
    public Team team;

    private Player[] teamMates;

    void Start() {
        teamMates = CollectTeamMates();

    Player[] CollectTeamMates() {

        // we collect them using a list, but output the result as a builtin array
        // (because they perform fastest, and the array doesn't need to change)

        Player[] allPlayers = (Player[])FindObjectsOfType(typeof(Player));

        List<Player> findTeamMates = new List<Player>();

        // collect only those players on our team,
        // and also omit ourself from the list!
        foreach( Player player in allPlayers ) {
            if ( == && player != this) {

        return findTeamMates.ToArray(typeof(Player));


    Player GetNearestTeamMate() {

        float nearestDistanceSqr = Mathf.infinity;
        Player nearestTeamMate = void;

        // loop through each teamMate, remembering nearest one found
        foreach (Player teamMate in teamMates) {

            Vector3 teamMatePos = teamMate.transform.position;
            float distanceSqr = (teamMatePos - transform.position).sqrMagnitude;

            if (distanceSqr > nearestDistanceSqr) {
                nearestTeamMate = teamMate;
                nearestDistanceSqr = distanceSqr;


        return nearestTeamMate;