Search Unity

What is wrong with this script?

Discussion in 'Scripting' started by D3Jason1, Mar 24, 2013.

  1. D3Jason1

    D3Jason1

    Joined:
    Feb 18, 2012
    Posts:
    125
    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System;
    4. public class test : MonoBehaviour {
    5.    
    6.     IEnumerator Start ()
    7.     {
    8.         int a = 1;
    9.         int f = 1;
    10.         string url = "http://www.decadesband.com/uploads/2/8/0/0/2800976/song_data.csv";
    11.         WWW www = new WWW (url);
    12.         yield return www;
    13.         String [,] basic = new String [2,7];
    14.         String [] split = www.text.Split(new Char [] {',',' '});
    15.         foreach (String s in split)
    16.         {
    17.             if(a<3)
    18.             {
    19.                 basic[a,f] = s;
    20.                 f += 1;
    21.                 if(f>7)
    22.                 {
    23.                     f=1;
    24.                     a+=1;
    25.                 }
    26.             }
    27.         }
    28.         Debug.Log(basic[1,5]);
    29.     }      
    30.  
    31.     void Update ()
    32.     {
    33.    
    34.     }
    35. }
    Error log i recieved
    IndexOutOfRangeException: Array index is out of range.
    test+<Start>c__Iterator0.MoveNext () (at Assets/test.cs:19)
     
    Last edited: Mar 24, 2013
  2. EliteMossy

    EliteMossy

    Joined:
    Dec 2, 2012
    Posts:
    513
    Means you are trying to access a item in the array which does not exist for example:

    GameObject[] gos = new GameObject[10];

    we can see there should be 10 elements in the array. They start at 0 and end 9 (0 to 9 = 10), so if i did gos[10] i would get an out of range exception.
     
  3. stridervan

    stridervan

    Joined:
    Nov 11, 2011
    Posts:
    141
    should be

    Code (csharp):
    1.  
    2. foreach (String s in split)
    3. {
    4.             if(a<2) // 3 changes to 2
    5.             {
    6.                 basic[a,f] = s;
    7.                 f += 1;
    8.  
    9.                 if(f>7)
    10.                 {
    11.                     f=1;
    12.                     a+=1;
    13.                 }
    14.             }
    15. }
    16.  
    since array indexes start from 0