- Home /
2D Array Tilemap Help [C#]
I'm trying to set up a basic 2D array to use a tilemap where the tile used is based on the integer in the array. I'm having trouble with which tile is being switched (it always seems to be up up one vertically).
2D array creation:
public int xMax = 3;
public int yMax = 3;
void Start () {
int[,] dungeonMap = new int[xMax,yMax];
PopulateDungeon(ref dungeonMap);
CreateDungeon(dungeonMap);
}
Filling dungeon with blank tiles and a test tile at (0,0):
public void PopulateDungeon(ref int[,] dungeonMap){
for(int x = 0; x < dungeonMap.GetLength(0); x++){
for(int y = 0; y < dungeonMap.GetLength(1); y++){
dungeonMap[x,y] = 1;
}
}
dungeonMap[0,0] = 2;
}
Instantiating/re-naming the tiles to the world:
public void CreateDungeon(int[,] dungeonMap){
Vector2 tileLoc;
Sprite spr;
SpriteRenderer sr;
GameObject test;
for(int x = 0; x < dungeonMap.GetLength(0); x++){
for(int y = 0; y < dungeonMap.GetLength(1); y++){
tileLoc = new Vector2((x*.16f), (y*.16f));
test = Instantiate(blankTile, tileLoc, Quaternion.identity) as GameObject;
test.name = (x + "," + y);
test.transform.parent = gameObject.transform;
spr = GetTile(dungeonMap[x,y]);
sr = blankTile.GetComponent<SpriteRenderer>();
sr.sprite = spr;
}
}
}
The output looks like this:
I can't for the life of me figure out why it is in the 0,1 instead of 0,0 position. Any help would be greatly appreciated!
Insert a Debug.Log line to check the tileLoc position. If it is 0,0, then maybe your sprite has it's pivot offset?
Answer by barbe63 · Jul 14, 2015 at 10:34 AM
Ok I think I got it!
You are calling a GetComponent on the Prefab instead of the instantiated GameObject, so it looks like you are setting the sprite for the next gameobject... which is 0,1 for 0,0!
Do like this instead:
sr = test.GetComponent<SpriteRenderer>();
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
2D Jagged Array , Array index is out of range. 3 Answers
Making a bubble level (not a game but work tool) 1 Answer
Values in Array Automatically Revert 1 Answer