C# Argument is out of range.

Hello, im making moving and randomly spawning background for my game. For now i got 3 different prefabs as background, i want to spawn randomly 1 of them every 2secs or smth. But i got error that Argument is out of range. Prameter name: index. Here’s my code:

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class BackGround : MonoBehaviour {

    List<GameObject> bgList = new List<GameObject>();
    public GameObject bg1;
    public GameObject bg2;
    public GameObject bg3;

    void Start(){
        StartCoroutine(bgSpawn());

        bgList.Add(bg1);
        bgList.Add(bg2);
        bgList.Add(bg3);
    }

    IEnumerator bgSpawn(){
        while (true) {

            int bgIndex = Random.Range(0, bgList.Count);
            Instantiate(bgList[bgIndex], transform.position, transform.rotation);
            yield return new WaitForSeconds(2.482f);
        }
    }
}

[bgIndex-1]
there are 3 things
0,1,2
note no 3

You calll StartCoroutine before you have added the items to the list. Swap the order.

1 Like

When you pass an int into Random.Range it will treat it as array index and do the -1 for you so bgIndex-1 is not needed.

http://docs.unity3d.com/ScriptReference/Random.Range.html

2 Likes

Thank you a lot! I couldn’t figure it out for like 5 hours :smile: It works just how i wanted to! //Sorry for my bad english.