Want to find closest NPC to the player character. How?

I want to find the closest NPC to the player character. What is the best to do this?

Some ideas I have had:
Every NPC has an extra collider and then calculate closest NPC using collider data (although not sure how i would actually go about this)
Raycasting?

Fattie’s answer is really good, although you might not always have a pool to work with (it is recommended to use a pool of objects - especially for mobile development). Certain situations demands specialized solutions. :slight_smile:

This solution is written especially for situations where a pool is difficult to manage. What you want to do is to name the script ClosestCollider.js and put it on your player. It uses an IComparer to sort the array returned from a Physics OverlapSphere using the magnitude of distance between the player and returned colliders.

#pragma strict
#pragma downcast
import System;

/*
	ClosestCollider.js
	Description: Finding closest collider without using a pool
	Last updated: 2012-12-28
	Author: save
*/

var sphereRadius : float = 10.0; //Radius of the OverlapSphere
var sphereMask : LayerMask; //What layers the OverlapSphere sees
var updateFrequency : float = 1.0; //Update frequency of FindClosestCollider-function

private var cachedUF : float; //Cached value of updateFrequency
static var pTransform : Transform; //Cache the Player Transform

function Start () {
	pTransform = transform;
	RestartInvokeRepeating();
}

//Finding the closest collider
function FindClosestCollider () {
	if (updateFrequency!=cachedUF) RestartInvokeRepeating();
	var pSphere : Collider[] = Physics.OverlapSphere(pTransform.position, sphereRadius, sphereMask);
	if (pSphere==null||pSphere.Length==0) return;
	System.Array.Sort(pSphere, new PositionSorter());
	DoSomethingWithClosestTransform(pSphere[0].transform);
}

//Do something with the closest transform, for instance print its name in Console
function DoSomethingWithClosestTransform (t : Transform) {
	Debug.Log(t.name);
}

//This is just a fancy extra if you want to update the frequency in play mode
function RestartInvokeRepeating () {
	updateFrequency = Mathf.Clamp(updateFrequency, .01, 10.0);
	CancelInvoke("FindClosestCollider");
	InvokeRepeating("FindClosestCollider", .0, updateFrequency);
	cachedUF = updateFrequency;
}


//Sort the closest transform
class PositionSorter implements IComparer {
	function Compare(a : System.Object, b : System.Object) : int {
	    if ( !(a instanceof Collider) || !(b instanceof Collider)) return;
	    var posA : Collider = a;
	    var posB : Collider = b;
	    return (ClosestCollider.pTransform.position-posA.transform.position).magnitude.CompareTo((ClosestCollider.pTransform.position-posB.transform.position).magnitude);
	}
}

Let me know if it needs improvements, tested and should be ready to roll.