Get firstgid property from tileset tag in .tmx level file

Hey there. In different levels, depending on the tilesets used, this firstgid property might change. It seems like the only way to keep them the same is to have the same layers in the same order in every level file, and I’m not even sure this would ensure the firstgid is the same. So, I need to get it programmatically for each tileset per level. How do I do this?

 <tileset firstgid="1" source="../StaticObjects.tsx"/>
 <tileset firstgid="89" source="../BackgroundBricks.tsx"/>
 <tileset firstgid="105" source="../BoxDrawing.tsx"/>

foreach (TiledMapTileset tileset in map.Tilesets) {
    int firstGid = tileset.FirstGid; //FirstGid isn't a real property

I used this a while back. Not sure if it still works though - I had TileSet issues with the upgrade to 3.8.1 which i have not resolved yet.

        private int GetTileId(TiledMap map, TiledMapTileset tileSet, int id)
            int firstGid = map.GetTilesetFirstGlobalIdentifier(tileSet);          
            if ((id >= firstGid) && (id < firstGid + tileSet.TileCount))
                    return id - firstGid;
            return -1;
1 Like

Thanks! I overlooked GetTilesetFirstGlobalIdentifier. The way you’re doing it there makes sense but I kludged this together for my purpose:

foreach (TiledMapTileset tileset in tiledMap.Tilesets) {
    string source = "";
	foreach (KeyValuePair<string, string> entry in tileset.Properties) {
		if (entry.Key == "source") {
			source = entry.Value;
    if (source == "../Walls.tsx") {
        Wall.firstGid = tiledMap.GetTilesetFirstGlobalIdentifier(tileset);

This way, my parser hinges on the filename of the tileset rather than the order of the layers or how many tilesets are present etc… I can also easily parse other XML properties of each named tileset here. Not totally ideal for each situation, but it works for situations where you have a specific tileset for a specific purpose in-game rather than splitting up one tileset into groups of purposes. I am doing both for some reason.