ArgumentOutOfRangeException: Argument is out of range - Can't fix need help :(

Hey all so I am undergoing the error as shown in the title. I can’t seem to solve it as I am not even sure as to why it is happening, anyways here’s the code creating the error.

The error occurs apparently at line which states:

diff = transform2[i + 1] - transform2[i];

```csharp
*public class xrotationcapsule : MonoBehaviour {

public Quaternion p;
public Quaternion t;
float cheekypoop = 90;
public Vector3 capsulemove;
int count1 = 0;
int count2 = 0;
int count3 = 0;
float pizza = 0.0f;
float diff;
float diff2;
string str;

List<float> transform2;

// Use this for initialization
void Start () {

    capsulemove = this.gameObject.transform.position;

    transform2 = new List<float> ();


    InvokeRepeating ("capsulerotation", 0f, 0.0001f);
  
}*</em>

*_ _*csharp
*void capsulerotation()
{

    for (int i = 0; i<transform2.Count; i++) {


        diff = transform2[i + 1] - transform2[i];

        if (diff >  0.015f)
        {

            str =  "left";

          


        }
        else if (diff < - 0.015f)
        {

            str = "right";
      

      
        }

        else if (diff == 0){

            str = "middle";

            if ( cheekypoop < 90 )
            {
                cheekypoop += 8.000f;

            }

            if ( cheekypoop > 90 )
            {
                cheekypoop -= 8.000f;
            }


  
        }




    }*</em>

```
Thanks in advance to those who help me out :slight_smile:

You’re looping through an array that goes from (let’s say) 0 to 15. In the last loop, i will be 15, so you’re then trying to access [i + 1], or index 16 - which doesn’t exist. You could make it only loop to transform2.Count - 1.

1 Like

Hey this was my assumption at first, but then I tried

diff = transform2[i] - transform2[i - 1];

which logically, would work as, as far as I know it means, transform[index(15)] - transform[index(14)] right?

but no I still got the exact same error strangely enough.

Nvm StarManta, thanks for the help I solved it by doing…

diff = transform2 - transform2[transform2.Count - 3];
I did -3 rather than -1 as transform2.Count is just a bit quicker updating than ‘i’ itself.
Thanks.