dynamic array index error

I don’t quite understand why I’m getting an “array index out of range” error.

I’ve a fairly simple code using a dynamic to activate enemies in certain zones:

    public Transform thePlayer;
    public GameObject[] enemy; // enemies to be activated using a dynamic array

    public float distanceToZone;

    void Update()
    {
        ActivateNme();
    }

    void ActivateNme()
    {
        //compares Distance(Vector3A, Vector3B);
        float playerDistance = Vector3.Distance(thePlayer.position, transform.position);

        if (playerDistance <= distanceToZone)
        {
            int enemyCount = (enemy.Length);
            print(enemyCount);
            enemy[enemyCount].SetActive(true);
        }
    }

I’m setting the size of the array in the inspector

The array index is there, yet I’m still getting this error.

Is there anything wrong with the syntax that’s causing this problem?

Thanks in advance

Could it be because the index is 0 based and your int enemyCount is not? Try

  • if (playerDistance <= distanceToZone)
  • {
  • int enemyCount = (enemy.Length);
  • print(enemyCount);
  • enemy[enemyCount - 1].SetActive(true);
  • }

Thanks @Magnumstar , this does get rid of the error but it’s only activating one out of “x”

Looks like you’ll need a loop. Instead of setting and using a enemyCount index, try a foreach loop, something like this…

if (playerDistance <= distanceToZone)
{
      foreach (Enemy singleEnemy in enemy)
      {
            singleEnemy.SetActive(true);
      }
}

Thanks for the feedback got it sorted…was just confused because I was using the code below to spawn enemies randomly & it works fine.

int spawnPointIndex = Random.Range (0, spawnPoints.Length);
        _nmeReference.transform.position = spawnPoints[spawnPointIndex].transform.position;