I am getting the above error and I tried to use debug.log to print where the error is. I am creating a type of tank obj. which fire to some instantiated obj. Instantiated object are attacker.
In update I am using foreach loop to loop through all the instantiated object. If found and If object are in range fire.
void Update () {
if (attacker!= null )
{
//Debug.Log("inside att");
attacker = FindObjectsOfType<Attacker>();
}
// fire only if attacker is in range
if (IfInRange() && attacker!= null && running)
{
faceTowardTarget();
Fire();
}
}
bool IfInRange()
{// run through all the instantiated attacker
foreach (Attacker currentAttacker in attacker)
This works fine but somethime give above.At the end in the console the loop goes on and on and currentAttacker is null in the end. I tried to print that in console. but it don't go in other if statement
{ //if attacker is in range
if (attacker != null )
{
Debug.Log(currentAttacker.GetComponent<Health>().isAlive);
if (Vector2.Distance(transform.position, currentAttacker.transform.position) < minDistance)
{
attackerPos = currentAttacker.transform;
return true;
}
}
if (currentAttacker == null)
{
Debug.Log("curre Attacker null");
running = false;
return false;
}
}return false;
}
Attacker have a simple health script wich deal with damage if hit by projectile.
Void update()
{
if (health <= 0)
{
**is there any better way to destroy an obj. If i destroy gameObject that error appear and it get stuck in foreach loop**
// Destroy(gameObject);
noOfKilled++;
isAlive = false;
scoreHolder.addScore(scoreValue);
}
}
Thank you so much for helping. I tried searching but unable to resolve this.
Update()
,if
check, swapIsInRange()
andattacker != null
. If not, you're going intoIsInRange()
with anull
attacker (Maybe). Now, you can remove your attacker null checks inIsInRange()
which could've made yourforeach
loop pop. Also,currentAttacker
is not going to be null, it just won't be in your list. You need to maintain a flag – jiveturkey