Can i chose game objects as parts of an array in a script ?
Hey guys i need some help...
I created a 2D array that is 10x10, Now i have to fill those arrays with game objects of a grid that is 10x10. Grid is create with 100 cells that each use this script. Now i don't have any easy way to put all this cell in arrays with a script, because the only way (that i know) is to create 100 public gameObject variables. That means i would have to chose each cell for a variable manually with editor. And do that 100 times for each cell with this script. That's why im looking for a solution within a script. If you know that solution please anwser below. And if you could please don't be mean, im new to Unity.
Thank you in advance.
Answer by dhore · Dec 13, 2015 at 02:40 AM
The easiest way that I can think of is if you make an empty gameobject and then add the 100 cell objects all as children to the empty object, then add the script to the empty object and use a loop like this:
GameObject[,] cells = new GameObject[10,10]; // the array
void Start()
{
// not sure what function you want it in, so I'll just put it here
for (int i = 0; i < transform.childCount; i++) // loops through all the children
{
cells[i/10, i%10] = transform.GetChild(i).gameObject;
}
}
Thx this works, but i have one more question. Im trying to make it so that each object/cell in the array will go true a switch loop. That swith loop consists of 4 cases, depending on which case it is it would change color. Do you have any advice ? Thx
You'd be looking for something like this:
for (int i = 0; i < cells.GetLength(0); i++)
{
for (int j = 0; j < cells.GetLength(1); j++)
{
// check cases here
// if it matches the case then:
cells[i,j].GetComponent<Renderer>().material = red$$anonymous$$aterial;
}
}
But ins$$anonymous$$d of "red$$anonymous$$aterial" you'd use whatever your material name is for that case. Just remember that you'll need to make a new material for every different colour - and then I'd suggest giving them to the script via public variables.