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!