Allpurpose Function that finds closest GameObject with Component X

Hello!

I had a piece of code checking for the closest GameObject that has Component “Food” attached. Like this:

GameObject[] allobjects=(GameObject[])GameObject.FindObjectsOfType<Food>();
float closestdis=Mathf.Infinity;
GameObject closestFood=null;
foreach (GameObject t_object in allobjects) {
	float dis=(transform.position-t_object.transform.position).magnitude;
	if(dis<closestdis) {
		closestdis=dis;
		closestFood=t_object;
	}
}

which worked fine. Now, I wanted to check for the closest GameObject that has the Component “Creature” attached. As this is more or less the same but with a different Component type, I tried to write a function that could find the closest GameObject with Component “x” attached. This function:

GameObject FindClosest (Type _component) {
	GameObject[] allobjects=(GameObject[])GameObject.FindObjectsOfType(_component);
	float closestdis=Mathf.Infinity;
	GameObject closest=null;
	foreach (GameObject t_object in allobjects) {
		float dis=(transform.position-t_object.transform.position).magnitude;
		if(dis<closestdis) {
			closestdis=dis;
			closest=t_object.gameObject;
		}
	}
	return closest;
}

which is called by doing this:

GameObject closestfood=FindClosest(Food);

However, this doesn’t work. Is what I want possible or do you have to copy and paste this code for every different ComponentType?

If you’re thinking about copying and pasting a bunch of code, just changing a type each time, chances are you want to be using Generics. Something like this…

GameObject FindClosest <TComponent>() where TComponent : MonoBehaviour
{
     GameObject[] allobjects=(GameObject[])GameObject.FindObjectsOfType< TComponent>();
     float closestdis=Mathf.Infinity;
     GameObject closest=null;
     foreach (GameObject t_object in allobjects) {
         float dis=(transform.position-t_object.transform.position).magnitude;
         if(dis<closestdis) {
             closestdis=dis;
             closest=t_object.gameObject;
         }
     }
     return closest;
 }

You’d call it using lines like

GameObject closestFood = FindClosest< Food >();

Call :

GameObject closestfood=FindClosest(typeof(Food));