- Home /
Hi , i have Gameobject [] that uses gamobject.find , in every second.i think it will become a bottleneck so i cache in start, but then i have obj.ref error after destroy
void UpdateTarget()
{
float ShortDistance = Mathf.Infinity;
GameObject NearestEnemy = null;
GameObject[] enemies = GameObject.FindGameObjectsWithTag ("Greens");
foreach (GameObject enemy in enemies)
{
float DistanceToEnemy = Vector2.Distance (transform.position, enemy.transform.position);
if (DistanceToEnemy < ShortDistance)
{
ShortDistance = DistanceToEnemy;
NearestEnemy = enemy;
}
}
if (NearestEnemy != null && ShortDistance <= range)
{
target = NearestEnemy.transform;
}
//for now player is target even if friendly..
else if (Relations.B_isFriendWithRed) {
target = null;
}
else
target = player.transform;
}
Comment
Answer by Captain_Pineapple · May 04, 2018 at 11:03 AM
If i understand your problem correctly you have 2 options:
First: Don't destroy objects but simply disable them. Then you have to check if the gameObject is active when iterating them but this should only be a small amount of load for the programm.
Second: Iterate the objects not by foreach but by using a for(int i=0;i<enemies.Length;i++)
and access the lists entry by the index i. This way C# will not automatically try to access the lists entry and you can check for enemies[i] != null
before you try to do something with the object.
hope that helps.