I'm trying to programmatically add tiles and objects to a 2D scene. I have a tilemap with a lower number layer and an empty game object with a higher number layer that will contain the objects.
Problems:
- My Tilemap always draws on top of the objects.
- My objects draw (not surprisingly) in the order I create them. However, I want the objects further away from the camera to be drawn behind objects closer to the camera.
Example for one cell in the grid:
// Set tile for the tilegrid
Vector3Int tilePos = new Vector3Int(i, j, 0);
groundMap.SetTile(tilePos, groundTile);
// Place object as if it were standing on that tile cell
Vector3 objPos = new Vector3();
objPos.x = 1.0f*tilePos.x + 0.5f;
objPos.y = 1.0f*tilePos.y + 0.5f*objectHeight;
GameObject obj = GameObject.Instantiate(objectPrefab, objPos, Quaternion.identity) as GameObject;
obj.layer = objectParent.layer;
obj.transform.SetParent(objectParent.transform);
Solutions?
- I really have no idea about this one. I thought that the layers were supposed to handle the draw order. When I run the project, the objects have a higher layer number, but they are hidden behind the grid.
- I could easily just draw my tiles in the opposite order, but I didn't know if there was a different way to do this. I have been having the same issue with my player sprite being either drawn completely on top of an object or under it. However, I want the object to be on top when the player is behind it and on top with the player is in front of it. Any suggestions are appreciated.
Disclaimer: I'm a programmer but still pretty new to Unity. I tend to do as much as possible in the scripts, but I am very open to learning more about Unity's native tools.