ArgumentOutOfRangeException: Argument is out of range. (591894)

The error seemingly occurs at random times, usually during rounds 3 or 4.

    IEnumerator StartNextRound () {
        coroutineRunning = true;
        yield return new WaitForSeconds (5);
        round += 1;
        StartCoroutine (RoundNotification ());
        roundTotalText.text = round.ToString ();
        if (round <= 10) {
            zombiesToSpawn += 2.4f;
            zombieHealth += 100;
        }
        if (round > 10) {
            zombiesToSpawn = 24 * round * 0.15f;
            zombieHealth *= 1.1f;
        }
        zombiesToSpawn = (int)Mathf.RoundToInt (zombiesToSpawn);

        for (int i = 0; i < zombiesToSpawn; i ++) {
            int randomSpawner = Random.Range (0, activeSpawners.Count);
            Vector3 spawnLocation = new Vector3 (activeSpawners[randomSpawner].transform.position.x + Random.Range (0f, 4f),
                                                 activeSpawners[randomSpawner].transform.position.y,
                                                 activeSpawners[randomSpawner].transform.position.z + Random.Range (0f, 4f));
            GameObject spawnedZombie = (GameObject) Instantiate (Resources.Load ("Zombie"), spawnLocation, activeSpawners [randomSpawner].transform.rotation);
            zombies.Add (spawnedZombie);
            zombies[i].GetComponent <Zombie> ().health = zombieHealth;
            yield return new WaitForSeconds (Random.Range (0, 5));
        }
        coroutineRunning = false;
    }

EDIT - After looking at the docs, random range wont include the max, so the below is wrong.

I think this is the error

 int randomSpawner = Random.Range (0, activeSpawners.Count);

change it to this

 int randomSpawner = Random.Range (0, activeSpawners.Count - 1);

Would explain why it seems to be happening at random as well.

1 Like

Oh, I thought Random.Range was (inclusive, exclusive), but you’re right, thanks man.

zombies[i].GetComponent<Zombie>().health= zombieHealth;

This is a pointless complication- just use GetComponent on the spawnedZombie reference instead.

What HiddenMonk says is probably correct- I think the documentation for this is wrong.

I edited my post, I think I was wrong.
Edit - unless if its true that the docs are wrong
Edit 2 - after testing, I think the docs are right, so the error must be from something else, or has your issue stopped?

Do a check to make sure the that the activeSpawners list isn’t zero.

Btw, the documentation WAS wrong, but is NOW correct, which was what caused the confusion there.

Ok, the problem did persist until I did what Lysander recommended and now everything works as intended.

Just to be clear on Random.Range; this is the line I should use?

int randomSpawner = Random.Range (0, activeSpawners.Count);

Or should I subtract 1 from activeSpawners.Count?

do not subtract 1, the max will not be included. The docs are correct.

3 Likes