- Home /
Question by
LT23Live · Aug 12, 2014 at 09:51 PM ·
gameobjectarrayarraysfindobjectsoftype
How to Narrow Down an Array casted from FindObjectsOfType
void FindClosestEnemy(GameObject target) {
if (openBattle == true )
{
GameObject[] gos;
gos = Object.FindObjectsOfType(typeof (Stats_Script));
GameObject closest;
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (GameObject go in gos) {
Vector3 diff = go.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance) {
closest = go;
target = closest;
distance = curDistance;
}
}
// return closest;
}
}
Above is the code I'm trying to adjust. after the line gos = Object.F... I want to narrow the GameObject Array down to GameObject's with a bool set to true. Any other object should be discarded. How can I do this? ` //(gameObject.GetComponent
Comment
Answer by mediumal · Aug 12, 2014 at 11:51 PM
I don't think that code even compiles. Anyway, you want to do something like this:
GameObject FindClosestEnemy(GameObject target)
{
GameObject closest = null;
if (openBattle == true)
{
Stats_Script[] statScripts = UnityEngine.Object.FindObjectsOfType<Stats_Script>();
float distance = Mathf.Infinity;
Vector3 position = transform.position;
foreach (Stats_Script statScript in statScripts)
{
if (true == statScript.myBool)
{
Vector3 diff = statScript.transform.position - position;
float curDistance = diff.sqrMagnitude;
if (curDistance < distance)
{
closest = statScript.gameObject;
target = closest;
distance = curDistance;
}
}
}
}
return closest;
}