array index out of range. semi tower defence

this part of the script stops working after 19 cycles because of the error.
the error is on this line.

if (ownTowers*.gameObject.GetComponent<TowerControler>().typeOfTower == TowerControler.towerType.broken)*

and here is the whole iEnummerator
IEnumerator TowerCheck ()

  • {*

  •  yield return new WaitForSeconds (0.5f);*
    
  •  GameObject [] ownTowers;*
    
  •  resourceManager RM = resourceManager.GetComponent<resourceManager> ();*
    
  •  ownTowers = GameObject.FindGameObjectsWithTag ("EnemyBT");	*
    
  •  Debug.Log ("own Towers: " + ownTowers.Length);*
    
  •  upResourceTimer ++;*
    
  •  upTowersTimer ++;*
    
  •  if (upResourceTimer >= 120 && resourceUpgrades < upResourceTo )*
    
  •  {*
    
  •  	RM.AIResourceRate -= 0.2f;*
    
  •  	upResourceTimer = 0;*
    
  •  }*
    
  •  if (ownTowers.Length >= 1f)*
    
  •  {	*
    
  •  	for (int i = 0; i <= ownTowers.Length; i++)*
    
  •  	{*
    

_ if (ownTowers*.gameObject.GetComponent().typeOfTower == TowerControler.towerType.broken)_
_
{_
_
RepairTeam = true;_
_
}_
_
}_
_
yield return new WaitForSeconds (5f); _
_
}_
_
StartCoroutine(TowerCheck());_
_
}*_

“ownTowers” is the array whose index goes out of range.

Probably due to this line:

for (int i = 0; i <= ownTowers.Length; i++)

Instead of “<=” use “<”.

for (int i = 0; i <= ownTowers.Length; i++)

Should be

        for (int i = 0; i < ownTowers.Length; i++)

Remember computer programmers start counting at 0, not 1. So the last index of an array with 20 elements is actually 19.