trying to get gameobjects assigned to Array[x,y]

i have been looking at all the answers and i am really new at the unity so please bear with me.

if have 3 scripts. one to maintain an 2d array

public class Grid
    public static Element[,] elementArray = new Element[5, 5];

this references a script i attached to a prefab gameobject:

public class Element : MonoBehaviour {
//starts at -1 to due to the loops in gamesetup script
public static int locX = -1;
public static int locY = -1;
int x = (int)locX;
int y = (int)locY;
Grid.elementArray[locY, locX] = this;

lastly i have a script to build up a variable sized puzzlefield with gameobjects:

public void GenerateGrid()

        GameObject cellInputField;
        RectTransform rowParent;
        for (int rowIndex = 0; rowIndex < numOfRows; rowIndex++)
            rowParent = (RectTransform)Instantiate(panelRow);
            rowParent.transform.localScale =;
            Element.locY += 1;
            Element.locX = 0;
            for (int colIndex = 0; colIndex < numOfColumns; colIndex++)
                cellInputField = (GameObject)Instantiate(cellgrid);
                cellInputField.GetComponent<RectTransform>().localScale =;


in the test i am trying to build a grid of 5 by 5 so 25 gameobjects but i 25 times the same error:

IndexOutOfRangeException: Array index is out of range.
Element.Start () (at Assets/Element.cs:37)

if i understand the message correctly i am still not passing the correct [x,y] location to the array so that the gameobject is stored in the correct position. but i am complete missing a solution to this issue. i hope anyone can help me.

ah never mind i found the solution…

i changed the LocX and LocY away from Static and added the below the generateGrid part.

Element instance = cellgrid.GetComponent<Element>();

this solved it. this way i can call the correct instances of LocX and LocY while creating the grid and update them correctly for each copy gameobject.