Search Unity

IndexOutOfRangeException: Array index is out of range.

Discussion in 'Scripting' started by shuskry, Jan 12, 2018.

  1. shuskry

    shuskry

    Joined:
    Oct 10, 2015
    Posts:
    462
    Hi everybody , i'm trying to make read a String to array of float but i'm have this error message :

    IndexOutOfRangeException: Array index is out of range.
    ArrayMovementReader.ReadString (System.String stringarray) (at Assets/ArrayMovementReader.cs:23)

    I had look on Google and i find nothing :/

    Here my code :

    Code (CSharp):
    1. using System;
    2. using System.Collections;
    3. using System.Collections.Generic;
    4. using UnityEngine;
    5.  
    6. public class ArrayMovementReader : MonoBehaviour {
    7.  
    8.     public float[] floatMove;
    9.  
    10.     public List<float[]> ArrayToRead = new List<float[]>();
    11.  
    12.     bool isReading = false;
    13.  
    14.     public void ReadString(string stringarray)
    15.     {
    16.         stringarray.Replace(".", "");
    17.  
    18.         string[] arrayString = stringarray.Split('$');
    19.         for (int i = 0; i < arrayString.Length; i++)
    20.         {
    21.             string[] finalArray = arrayString[i].Split('%');
    22.  
    23.             floatMove[0] = float.Parse(finalArray[0]);
    24.             floatMove[1] = float.Parse(finalArray[1]);
    25.  
    26.  
    27.             ArrayToRead.Add(floatMove);
    28.         }
    29.     }
    30. }
    31.  
    If someone can help me i'll really appreciate :D!

    Have a good day !
     
  2. pk_Holzbaum

    pk_Holzbaum

    Joined:
    Jul 26, 2012
    Posts:
    95
    It seems you never initialize your floatMove Array.

    Something like this:
    Code (CSharp):
    1. public float[] floatMove = new float[2];
     
  3. DonLoquacious

    DonLoquacious

    Joined:
    Feb 24, 2013
    Posts:
    1,667
    ^^ this. You haven't resized floatMove- it's likely a zero-element array (automatically initialized when serialized in the inspector) so when you try setting the first and second elements, it throws an error. I would make floatMove private and initialize it to 2 elements- if you leave it public, put [NonSerialized] or [HideInInspector] on the field, so the inspector initialization doesn't override the length of the array you set there.

    Alternatively, just put the array definition in the loop (line 22), instead of making it a field at all.
     
  4. shuskry

    shuskry

    Joined:
    Oct 10, 2015
    Posts:
    462

    Edit: All work! Thanks all! :)
     
    Last edited: Jan 12, 2018