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.SetParent(Gridset);
rowParent.transform.localScale = Vector3.one;
Element.locY += 1;
Element.locX = 0;
for (int colIndex = 0; colIndex < numOfColumns; colIndex++)
{
cellInputField = (GameObject)Instantiate(cellgrid);
cellInputField.transform.SetParent(rowParent);
cellInputField.GetComponent<RectTransform>().localScale = Vector3.one;
}
}
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.
Answer by DevMagi · Feb 01, 2017 at 10:31 PM
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.
Your answer
![](https://koobas.hobune.stream/wayback/20220612110121im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Get gameObjects from a protected GameObject array of base class in derived class 1 Answer
Showing different objects OnMouseDown 1 Answer
How can i add a gameobject configured already on a unity application without rebuild this? 0 Answers
destroying instantiated groups of objects 1 Answer
Bad practice to create a GameObject for every BoxCollider2D? 0 Answers