ArgumentOutOfRangeException: Argument is out of range.

I have been looking at the different posts in this forum about this problem but I couldn’t find anything that answers my problem. I am new to programming so this error is new to me. Can anyone help me find out what I did wrong with my code? Thanks.

public class move : MonoBehaviour {

    public float Speed = 5;
    public GameObject randomWall;
    public List<GameObject> myWalls;
    int curIndex = 0;


    void Start()
    {
        RandomWALLS();
    }

    void Update()
    {
        movingWalls();
        //Invoke("movingWalls",5);
    }

    void movingWalls()
    {
        for (int ctr = 0; ctr <= myWalls.Count; ctr++)
        {
            if (randomWall == null) RandomWALLS();
				

            float amtToMove = Speed * Time.fixedTime;

            randomWall.transform.Translate(Vector3.back * amtToMove, Space.World); 

            if (randomWall.transform.position.z < -10)
            {
                GameObject.Destroy(randomWall);

                randomWall = null;
                RandomWALLS();
                if (myWalls.Count > 0)
                {
                    myWalls.RemoveAt(curIndex);
                }
            }
        }
    }
    void RandomWALLS()
    {
        curIndex = Random.Range(0, myWalls.Count);
        randomWall = myWalls[curIndex];
    }

The error points to this part of the code: randomWall = myWalls[curIndex];

I would think your issue is here:

for (int ctr = 0; ctr <= myWalls.Count; ctr++)

you should not use <= but only <.

Let’s say your list has 5 items, a list or array index always starts from 0. That is your list has 0,1,2,3,4. Now the count variable returns how many items are there which is 5.

Because your loop uses <= myWalls.Count, it tries to find the index 5 that is out of range.