- Home /
Spawning GameObjects with help of classes --- Attaching classes to GameObjects
Hello! It's my very first time asking a question here, I haven't found out how to solve this problem, thank you very much!
I have this class ( in TileControl.cs )
public class Tiles{
public GameObject tileGO;
public float xPos;
public float yPos;
public bool isLight;
}
I have a 2-dimensional array called TilePosition, which is empty, so the script Levels.cs fills it. Here's an example from Levels.cs
if (levelNumber == 0)
{
rows = 3; columns = 4;
TileControl.tilePosition = new int[,] {{ 0, 1, 1, 1 },
{ 1, 1, 1, 0 },
{ 0, 1, 1, 1 }};
}
And if I call BuildMap.GenerateMap( Levels.rows, Levels.columns ) it works as you can see here:
Here is the actual problem: If all the tiles are called ''Cube'', how do I distinguish them? How could I attach the class Tiles to every Cube?
If all the cubes had xPos, yPos and isLight variables, I could easily work with them. For example, I could delete all the cubes whose xPos is 2, or color them red, etc.
( Sorry for my English or if I wasn't clear ) Thank you!
( There are 9 tiles in the picture, but 18 in the Hierarchy, because there will be dark tiles behind light tiles, but that is not important )
Answer by Cherno · Mar 21, 2015 at 08:49 PM
How about this:
Add a bool "filled" to your Tiles class. Then instead of a 2-dimensional int array you create a 2-dimensional tiles array and for each Tiles in it, set the filled value to true or false (what was 0 or 1 in the int array). Now you can access each cube by passing the x and y values to the Tiles array.
Thank you for your help Cherno, I'm going to try it and reply later
Great, it works, thank you, but now I've encountered another problem. The tiles are deleted whenever I try to refer to them outside of the void Generate$$anonymous$$ap.
This is my Tiles array:
TileControl.Tiles[,] tilePosition = new TileControl.Tiles[Levels.columns, Levels.rows];
I can give them xPos, yPos and state( 0 or 1 ):
for(int j=0; j<row; j++)
{
for(int i=0; i<col; i++)
{
Debug.Log(i + " " + j);
tilePosition[i, j] = new TileControl.Tiles();
tilePosition[i, j].xPos = i;
tilePosition[i, j].yPos = j;
tilePosition[i, j].state = TileControl.map[j, i];
}
}
I can test whether they are filled or not:
int empty = 0;
int filled = 0;
for(int j=0; j<row; j++)
{
for(int i=0; i<col; i++)
{
if(tilePosition[i, j].state == 1) filled++;
else empty++;
}
}
Debug.Log("Filled: " + filled + " Empty: " + empty);
Debug.Log("Lenght: " + tilePosition.Length);
This means: filled = 9; empty = 3; length = 12;
When I try to get the array's length from somewhere else, it's 0 and boom, ''Array index is out of range'' :(
Problem solved, the last reply was a week ago, so I marked your answer.