how do I only pick up items in range on key press?

I made a script that should be saying "if gameObject is within 5f of the player, and the player presses β€œE” then gameObject will be destroyed. So the problem is that I have multiple duplicates of the gameObject in my scene that are scattered throughout the scene, yet when i press E, all of them are destroyed, instead of only the ones that are within 5f. My code is below for to help explain :slight_smile:

Thank you so much!

First of all FindGameObjectWithTag("") is a heavy method and should be used with caution.

Next if the pickup items have scripts on them then something like this would work:

Collider[] cols = Physics.OverlapSphere(transform.position, RANGE);
foreach (Collider col in cols) 
{
     PICKUPSCRIPT pickup = col.GetComponent<PICKUPSCRIPT>();
     if (pickup != null) 
     {
          // Pickup
     }
}

Else if they don’t have scripts and only tags then some similar code like this would work:

     Collider[] cols = Physics.OverlapSphere(transform.position, RANGE);
     foreach (Collider col in cols) 
     {
          if (col.tag == "pickup") 
          {
               // Pickup
          }
     }

One of these should work. Another word of caution is that this should only be used when key or button pressed not every frame.