Sorting items on ground by distance

So I have an item system in place, and the player is able to pick up items.

When the player get’s close to an item he can pick up, a GUI message appears saying “Press e to pick up item”. But when many items on the ground are right near eachother, The gui message appears for all of them, and pressing E will pick them all up at the same time.

I would like it so that only the item closest to the player is picked up, and GUI message is displayed, but I don’t know how to go about it. Can someone point me in the right direction please?

Here is the code I’m using to pick up an item (This script is attached to every item on the ground)

public class PickUpItem : MonoBehaviour {
	
	private Transform player;
	private float distance;
	private GUISkin label;
	// Use this for initialization
	void Start () {
		player = GameObject.FindGameObjectWithTag("Player").transform;
		label = Resources.Load("GUISkins/Inventory GUISkin") as GUISkin;
	}
	
	// Update is called once per frame
	void Update () {
		distance = Vector3.Distance(player.position, transform.position);
		
		if (Input.GetKeyUp(KeyCode.E) && distance < 2) {
			Destroy(gameObject);
			Menus.Inventory.Add(ItemDatabase.itemPresets[gameObject.name]);
		}
		
	}
	
	void OnGUI() {		
		GUI.skin = label;
		if (distance < 2) {
			GUI.Label(new Rect(Screen.width/2 - 125, Screen.height/2 - 200, 250,25), "Press E to pick up " + gameObject.name, "Label");
		}	
	}
}

So to recap, I just need a way to tell which item on the ground is closest to the player.
(I believe GameObject.FindGameOBjectsWithTag and then sorting the array might be an option, but I am still unsure of how to even implement that)

Thanks!

GameObject.FindGameOBjectsWithTag

will give you all the objects with the tag in the scene (all the items).

This will give you even items that are vary far aways, which is an overhead.

Maybe you can try using this: Physics.OverlapSphere
on your player.

Once that is done, you need to sort the array like you said.

For sorting an array, you will to use loops ( for (int i=0; i<… )

I think you can just google “array sorting” and you should find the implementation.

You could just set a bool on the player like “isBusy” or something and have the item script change that value. Then each item could check that to see if it should show itself.

void OnGUI() {     
       GUI.skin = label;
       if (distance < 2 && !player.isBusy) {
         GUI.Label(new Rect(Screen.width/2 - 125, Screen.height/2 - 200, 250,25), "Press E to         pick up " + gameObject.name, "Label");
       } 
    }