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?