Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

C# script help

Discussion in 'Scripting' started by Mateusz Gryczan, May 10, 2014.

  1. Mateusz Gryczan

    Mateusz Gryczan

    Joined:
    May 10, 2014
    Posts:
    10
    i have error: IndexOutOfRangeException: Array index is out of range.

    Code (csharp):
    1. using UnityEngine;
    2. using System.Collections;
    3.  
    4. public class Zadanie_3 : MonoBehaviour {
    5.  
    6.    
    7.     int[,] tablica_2D = new int[10,10];
    8.     // 4x2x7
    9.  
    10.    
    11.     void Start ()
    12.     {
    13.         for(int a = 0; a < tablica_2D.Length; a++)
    14.         {
    15.             for(int b = 0; b < tablica_2D.Length; b++)
    16.             {
    17.                 Debug.Log(tablica_2D[a,b]);
    18.             }
    19.         }
    20.     }
    21. }
    22.  
     
  2. shaderop

    shaderop

    Joined:
    Nov 24, 2010
    Posts:
    942
    Because your array is multi-dimensional, you need to use Array.GetLength instead of just Length.
     
  3. Mateusz Gryczan

    Mateusz Gryczan

    Joined:
    May 10, 2014
    Posts:
    10
    how it will look?
     
  4. Jasper-Flick

    Jasper-Flick

    Joined:
    Jan 17, 2011
    Posts:
    951
    Your 2D array has two different lengths, one per dimension. Even if they're the same. If they're always 10, then you could just use a constant value. But in general, you'd need to use something like

    Code (csharp):
    1.         for(int a = 0; a < tablica_2D.GetLength(0); a++)
    2.         {
    3.             for(int b = 0; b < tablica_2D.GetLength(1); b++)
    4.             {
    5.                 Debug.Log(tablica_2D[a,b]);
    6.             }
    7.         }
    Length refers to the total array length, which would be 10 * 10 = 100 in this case. That's why you went out of bounds.
     
    Last edited: May 10, 2014
  5. Mateusz Gryczan

    Mateusz Gryczan

    Joined:
    May 10, 2014
    Posts:
    10