How to get your collider to see multiple triggers from other objects

Working on a project and kinda new to unity. Wanted to make a game with a character that is able to go around a pick up objects and notifies the player when they are in range of an object to pick up. Is there a way that the collider on the player can pick up both objects and tell the player there are multiple objects to in a clean way without having to write out the different tag combinations. Any other code advice or ideas would be nice too.

private void OnTriggerStay(Collider other)
{
if (other.gameObject.CompareTag(“Scoin”))
{
notify.text = “Press [e] to pick up coin Siver Coin”;
if (Input.GetKey(KeyCode.E))
{
totalCoins += SilverCost;
Destroy(other.gameObject);
coinText.text = "Coins: " + totalCoins;
notify.text = " ";
}
}
else if (other.gameObject.CompareTag(“Gcoin”))
{
notify.text = “Press [e] to pick up coin Gold Coin”;
if (Input.GetKey(KeyCode.E))
{
totalCoins += GoldCost;
Destroy(other.gameObject);
coinText.text = "Coins: " + totalCoins;
notify.text = " ";
}
}
}
private void OnTriggerExit(Collider other)
{
notify.text = " ";
}

You can make use of the trigger colliders you allready got on the pickups. Let’s say you want to get all colliders within a certain radius around an arbitrary center position, you can do this:

Collider[] hitColliders = Physics.OverlapSphere(center, radius);

The according GameObject can be recieved from each collider afterwards.

You can also provide a Layer to this function and set all your pickups to that layer so you don’t have to filter out the results by hand. The Overlap functions are using PhysX and its internal octree so performance wise this should be pretty usable.


Check:


btw:
TriggerEnter, -Stay and -Exit are only working if you are moving the player “physically” but not if you are modifying the transform directly. Furthermore you either have to be in playmode or add the ExecuteInEditmode attribute to your MonoBehaviour.


EDIT: Since you’re saying you’re new to unity, here’s another hint; Consider using Coroutines. If you don’t know about them yet, they give you the ability to execute pieces of code more or less “asynchronously” (but still in the main thread). You could for example refresh the list of pickups around you every 2 seconds (or only when the player is moving and so on) and then when the player presses the key, get the closest pickup out of that list.

public class ColliderDetector : MonoBehaviour {    
	public Transform player;
	public float radius = 2f;
	public LayerMask layer; 
	public Collider[] collisions;

	void Start() {
		StartCoroutine ("DetectPickups");
	}

	IEnumerator DetectPickups() {                
		while (true) {
			collisions = Physics.OverlapSphere (player.position, radius, layer);

			yield return WaitForSeconds (2f);
		}    	
	}
}

I didn’t test this snippet.