For my game I need to find the two closest gameobjects with a tag.
Help?
For my game I need to find the two closest gameobjects with a tag.
Help?
Eventually I worked it out and managed to convert a old Unity 3 script i found on another question to one that works seamlessly on Unity 5.6.
void Update()
{
gos = GameObject.FindGameObjectsWithTag(“Player”);
first = FindClosestEnemy(gos);
second = Find2ndClosestEnemy(gos, first);
Debug.Log("1st " + first);
Debug.Log("2nd " + second);
if (first == Owner)
{
Active = second;
}
else
{
Active = first;
}
if (Active != null)
{
var lookPos = Active.transform.position - transform.position;
lookPos.y = 0;
var rotation = Quaternion.LookRotation(lookPos);
transform.rotation = Quaternion.Slerp(transform.rotation, rotation, Time.deltaTime * 5);
}
}
GameObject FindClosestEnemy(GameObject[] gos)
{
GameObject Closest = null;
float distance = Range;
var position = transform.position;
foreach (GameObject go in gos) {
var diff = (go.transform.position - position);
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
Closest = go;
distance = curDistance;
}
}
return Closest;
}
GameObject Find2ndClosestEnemy(GameObject[] gos, GameObject FirstNear)
{
GameObject closest = null;
float distance = Range;
var position = transform.position;
foreach (GameObject go in gos) {
var diff = (go.transform.position - position);
var curDistance = diff.sqrMagnitude;
if (curDistance<distance && go !=FirstNear) {
closest = go;
distance = curDistance;
}
}
return closest;
}
}