[SOLVED] Index was outside the bounds of the array ??

I’m using array to insert 4 elements that left hand of my character will move between theme one by one. The problem is that it tells me “IndexOutOfRangeException: Index was outside the bounds of the array.” !!

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

public class Iks: MonoBehaviour
{

    public clickme _active;
    public bool reload;
    public int currt;
    public float dis;
    public Transform[] reloadPositions; // 4 elements


    void Start()
    {

        foreach (Transform trans in gameObject.GetComponentsInChildren<Transform>())
        {

            if (trans.name == "set")
            {
                reloadPositions[3] = trans.gameObject.transform;
            }
            if (trans.name == "set (1)")
            {
                reloadPositions[0] = trans.gameObject.transform;
            }
            if (trans.name == "set (2)")
            {
                reloadPositions[1] = trans.gameObject.transform;
            }
            if (trans.name == "set (3)")
            {
                reloadPositions[2] = trans.gameObject.transform;
            }
        }
       

    } // end start


    void Update()
    {


        currt = reloadPositions.Length;
        if (reload == true && _active.grenade == false)
        {
            dis = Vector3.Distance(_active.leftHandObj.transform.localPosition, reloadPositions[currt].transform.localPosition); // error in this line
            if (dis < 0.1)
            {
                currt = currt + 1;
                if (currt >= reloadPositions.Length && dis < 1)
                {
                    currt = reloadPositions.Length - 1;

                    reload = false;
                    currt = 0;

                }
            }
            _active.leftHandObj.transform.localPosition = Vector3.MoveTowards(_active.leftHandObj.transform.localPosition, reloadPositions[currt].localPosition, Time.deltaTime / 1.0f);

        }
        else
        {
        //    _active.leftHandObj.transform.localPosition = Vector3.MoveTowards(_active.leftHandObj.transform.localPosition, reloadPositions[reloadPositions.Length - 1].localPosition, Time.deltaTime / 1.0f);
        }


    } // end update


}

You’re not saying which line threw the error, but I would bet it is line 23. If you haven’t filled the list before Start, then there is no [3] in the array.

Did you define them in the Inspector?

1 Like

I mention it on the end of line 50.

Yes. 4 elements.

Update:
Line 47, should be deleted ^-^’

Thank you guys.

Sorry, I didn’t see the comment buried to the right.

Above line 50, you set currt to be the length of the array. Then you access the reloadPositions[currt] which is past the end.

If an array’s length is 5, then the valid index positions in the array are 0 1 2 3 4, and never 5. Think of it as [ 0, 5 ) or “zero through almost 5.”

1 Like

It’s OK.
Thank you.