1

I'm writing a Unity Script that reads a CSV file (2D and all numeric), breaks it down into floats that are appended to a 2D float array. Here is my code:

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

public class LoadCalibration : MonoBehaviour
{
    public float[,] pc_array; // Reconstructed PC coefficient MD array (PCs as rows and variables as columns)

    // Start is called before the first frame update
    void Start()
    {
        // PC COEFFICIENTS

        pc_array = new float[20, 20];
        Debug.Log(pc_array);

        TextAsset pc_data = Resources.Load<TextAsset>("pc_coeff"); //Data is in as variables x PCs

        string[] variable = pc_data.text.Split(new char[] { '\n' }); // split pc_data into rows(each row is one variable, for all PCs)

        for (int i = 0; i < variable.Length - 1; i++)
        {
            string[] pc = variable[i].Split(new char[] { ',' }); // delegate each variable to a pc
            Debug.Log(i);

            for (int j = 0; j < pc.Length; i++)
            {
                Debug.Log(j);
                pc_array[j,i] = float.Parse(pc[j]); // Load float value into the pc_coeff MD array
            }

        }

    }
}

And it throws me this error:

IndexOutOfRangeException: Index was outside the bounds of the array.
LoadCalibration.Start () (at Assets/Scripts/LoadCalibration.cs:31)

Using Debug.Log() I have worked out that that the error occurs at i = 0 and j = 0 (the first index of the array), even though I declare it as a 20 x 20 array. I am new to C# so it may be very obvious what the error is but I can't work it out. Any help would be much appreciated!

I have used Debug.Log() to assess that the rest of the code is working (aka its reading the CSV file and converting each string entry into a single float point).

1
  • When doing Debug.Log() you should also include the name of the variable. This will likely make the problem jump right out at you. Commented Aug 15, 2019 at 15:48

1 Answer 1

4
  for (int j = 0; j < pc.Length; i++)

change to

  for (int j = 0; j < pc.Length; j++)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.