Order Objects Based on Proximity

Hi, all!

I am using Physics.OverlapSphere to get an array of all colliders in a certain range.

Currently in my script, it picks a random object. However, I would like to order these objects in the array based on proximity to the gameObject.

How would I go about this?

Thanks!- YA

You can use an inline function to sort an array:

var possibleTargets = Physics.OverlapSphere (transform.position, 100);
System.Array.Sort (possibleTargets,
	function (a : Collider, b : Collider)
		(transform.position - a.transform.position).sqrMagnitude.
		CompareTo ((transform.position - b.transform.position).sqrMagnitude));

You can also use an external function, which may be more readable, since it’s not all on one line:

System.Array.Sort (possibleTargets, DistanceSort);

function DistanceSort (a : Collider, b : Collider) : int {
	return (transform.position - a.transform.position).sqrMagnitude.
		CompareTo ((transform.position - b.transform.position).sqrMagnitude);
}

-Construct an array (or two, or associative, or hashtable) of distances between the gameObject and the colliders (Unity - Scripting API: Vector3.Distance )

-Sort the array

That’s pretty much it

Place this on an empty game object and it should give you every object in the blastRadius in order of closest first, needs altering to suit your requirements, amount, distance … ect.

#pragma strict

var myArray : String[] = new String[200];
var blastRadius : float = 100;

private var i : int;

function Start () {

	AreaDamageEnemies(transform.position, blastRadius);
}

function Update () {

}

function AreaDamageEnemies(location : Vector3, radius : int){

	var objectsInRange : Collider[] = Physics.OverlapSphere(location, radius);
					
    for (var col : Collider in objectsInRange){

		while(i < objectsInRange.length){			// Go through the objectsInRange array (objects in the Physics.OverlapSphere radius)
			myArray _= objectsInRange*.name;	// Add each GameObject.name to myArray*_

_ print(objectsInRange*.name);
i++;
yield;
}
}
}*_