After item is collected, point to the next closest item?

I will try to explain my problem…

I have a 3D map on which there are several identical keys that the player has to collect to unlock the door to a castle. Only when the player collects all keys will they be let into the castle. This part works, no problem.

I have a GUI navigation arrow that is able to point to a key on the map using WorldToScreenPoint. This part was a bit trickier, but it’s mostly working now.

My problem is: I want the navigation arrow to point to the next closest key on the map once the first key is collected, and continue doing this until all keys have been collected.

As it stands right now, the nav arrow stops functioning after the first key is collected and the game object is destroyed.

Does anyone have ideas on how to accomplish this? Is there a way to compute the closest of a set of game objects that all have the same tag?

Cheers,

cz2isq

you could use a static LsitArrray of all the keys.

EG

static public ListArray allKeys;

On key.awake() or start() add each key to the list.

allKeys.add(thisKey);

Then to point to the closets key simple use a loop thru all the keys

key closestKey = null
float closestKeyDistance = 0;

foreach (Key myLoopKey in allkeys)
{

if ( (! closestkey) ||
{
closetKey = myLoopKey;
closestKeyDistance = Vector3( soem sort of distance check);
}
else
{

if (myLoopKeyDistance < closestKeyDistance)

{
closetKey = myLoopKey;
closestKeyDistance = Vector3( soem sort of distance check);
}

}

Code is bad but you should get idea

For my own requirenments I wrote a function like this:

function GetObjectInRange(p_Type : System.Type) : Object
{
	var v3MyPosition				= transform.position;
	var fMinDistance				= Mathf.Infinity;
	
	var lObjects					= FindObjectsOfType(p_Type);
	var pObject : Object		= null;	
	
	for(var pObjectIterator : Object in lObjects)
	{
		fDistance = (pObjectIterator.transform.position - v3MyPosition).sqrMagnitude;
		
		if(fDistance < fMinDistance)
		{
			fMinDistance	= fDistance;
			pObject			= pObjectIterator;
		}
	}
	
	return pObject;
}

So you can use it like this:

m_pClosestObject = GetObjectInRange(MyObjectTypeHere);

Thank you both I will try both solutions.