Import Tiled Maps to Unity with Tiled2Unity

by Seanba on May 31, 2014

Tiled2Unity

(Note: ‘Minimalist’ example artwork is attributed to Blarget2 via OpenGameArt.org)

If you’ve been working on a 2D tile-based game in the last couple of years then there’s a decent chance you’re familiar with Thorbjørn Lindeijer’s excellent Tiled Map Editor. It’s what I used when creating the maps for Mega Man in Unity and I’ve now retooled and de-hacked my Tiled-to-Unity exporter (called Tiled2Unity Utility because naming things is hard) for general consumption by my fellow game developers  – free of charge under the MIT License. I sincerely hope others find it useful.

You can download the Tiled2Unity Utility from the Download Page.

Features:

  • Builds a Unity prefab out of your TMX map file
  • Supports all TMX layer formats (XML, CSV, Base64, gzip/zlib compressed)
  • Multiple layers and tilesets supported
  • Exports Object Layer as polygons, polylines, rectangles, circles
  • Tile Layer collisions supported (with slopes, odd-shaped polygons)
  • Polygon colliders can be concave, have holes, and be composed of separate polygons
  • Can assign Tag, Sorting Layer, Order in Layer, and (Physics) Layer of exported GameObjects through properties in Tiled
  • Support for customized creation of Unity Prefabs
  • Easy to use: In most cases, you simply export a TMX file into your Unity project and place the automatically generated prefab in your scene – no further edits needed

Limitations:

  • Orthographic map support only (Isometric and hexagonal map support in version 0.9.10.0)
  • Ellipse objects are ignored unless they are circular (there is no ellipse collider in Unity)
  • Object rotation is currently not supported (Object rotation added in version 0.9.9.0)
  • Tiled2Unity only runs on Windows out of the box (Prefabs exported into Unity will work on all devices though) (Note: See comments section here for support on other platforms)

Note that I made a purposeful decision not to support isometric maps*. It adds far too much complexity for something that I think is a bit of a hack. I feel orthographic maps should be used at all times and the illusion of top-down or side-scroller or isometric should come from the art, not some weirdo coordinate system. (Your mileage may vary but it’s not like the Nintendo Entertainment System had an isometric mode.)

*(Edit to add: Okay, I relent. Isometric and hexagonal map support has been added as of version 0.9.10.0.)

Tiled2Unity Uses Newer Features of the Tiled Map Editor

In order to assign collision data to tiles you will need to use the new Tile Collision Editor in Tiled.

Tile Collision Editor Menu Item

This Tiled feature is currently in beta* so you’ll need to get a version of the program from the daily builds here: http://files.mapeditor.org/daily/

For my development and testing I’ve used the May 23rd, 2014 build. (Builds older than April 24th, 2014 will crash if you have collision data in external tilesets.)

*(Edit to add: Not in beta anymore. Just download latest version of Tiled)

Getting Started with Tiled2Unity

Before you begin exporting Tiled data into Unity, your project needs to be aware of how it will import the *.unity2tiled.xml files that Tiled2Unity spits out. The scripts for this are part of the Tiled2Unity.unitypackage file found in the install directory.

There are two ways to import this package into your Unity project:

  1. From the Tiled2Unity install folder: Double click on the Tiled2Unity.unitypackage file
  2. From within Tiled2Unity: Just select the “Import Unity Package to Project” menu item

Import Tiled2Unity Unitypackage

In both cases, Unity will take you through the steps of installing the package into your Unity project. There’s a number of scripts and folders here. You’ll need them all.

Import all items

Now we’re ready to export some Tiled maps into Unity.

Using Tiled2Unity Examples

Your Tiled2Unity install contains a couple of TMX file examples. We’re going to open the minimalist.tmx file in Unity …

Minimalist map

We don’t need to run Tiled in order to export a TMX file into Unity, but I’ve set up a command in Tiled that will run Tiled2Unity for me.  This allows me to make my map edits in Tiled and then quickly export to Unity by pressing F5.

Setting Tiled2Unity command in Tiled

"c:\Program Files (x86)\Tiled2Unity\Tiled2Unity.exe" %mapfile c:\MyUnity\Test

The command is made up of 3 parts:

  1. The path to your Tiled2Unity install
  2. The %mapfile macro (this will be the same for all users)
  3. The path to your Unity project (you can leave this blank and use the Tiled2Unity GUI instead)

Hitting F5, now Tiled2Unity pops up with our map already loaded and ready to export to our Unity project …

Running Tiled2Unity from Tiled

Now, pressing the Big Ass Export Button will export an XML file (in this case, minimalist.tiled2unity.xml) to our Unity project where our importer scripts will create the meshes, textures, and materials needed and roll them all up into a prefab named after our TMX file.

Minimalist map in Unity

Now we can place the prefab into our scene hierarchy. (If our map was to be purely decorative then we’d be done.)

Minimalist prefab placed in scene

Adding Collision Geometry

Chances are most maps we make in Tiled for use in video games will require some collision geometry on them for sprites to interact with. Other solutions I’ve found on the internet or the Unity Asset Store require you to hand-place collision objects by hand in Tiled which I think is a total PITA. I’m going to show you how we can easily add complicated collision geometry (with holes, slopes, concave shapes, etc.) to our tile layers that are exported to Unity as PolygonCollider2Ds.

With Tiled still open on our minimalist map, bring up the Tiled Collision Editor an add a Rectangle or Polygon object that fully encloses the solid dark grey tile of our mini-tile tileset …

Add collision to tile

Let’s leave the other tiles alone for now and see how we’re doing. Press F5 again to bring up our Tiled2Unity exporter and press the Preview Exported Map button to see how the geometry would appear in Unity …

First collision preview

Here we can see how the geometry of just one tile will be combined into a polygon collider as the tile is repeated throughout the map. Note that, in the resulting collision mesh, there is actually four shapes here — two of which are rather awkward. Except for not matching the visuals, that’s actually okay, the PolygonCollider2D in Unity would handle this fine.

Let’s go back to Tiled and add polygons to our sloped tiles …

Adding sloped collision

(I recommend that Snap to Grid and/or Snap to Fine Grid is enabled when placing polygons in Tiled)

Previewing again we can see how sloped geometry will be added to the collision mesh …

Second preview

Again, this geometry could be exported into our Unity project and the PolygonCollider2D created from it would just work.

Going over all our darker tiles and adding polygons/rectangles I get a final preview that I’m pretty happy with …

Final preview

The best part of this is as we edit the map the collisions assigned to each tile move along with them. You add the geometry to your tiles once, create all the map data you like, and let the exporter take care of the rest.

Here’s the final exported prefab with our PolygonCollider2D in Unity …

Map with collision in Unity

And there you go, a 2D tile-based map, authored in Tiled, with collision, in your Unity scene.

Find any bugs? Is something not working as expected? Got a feature request that makes sense and won’t kill my social life? Feel free to email me.

By the way, the magic behind this polygon construction is courtesy of Angus Johnson’s exceptional (and open source) Clipper library. In my opinion, layer collisions is the most essential feature of Tiled2Unity and Johnson’s Clipper library worked for me the first time I tried to use it. C’est Magnifique! *kisses fingertips*

{ 16 comments… read them below or add one }

BaochaosDevs December 2, 2015 at 1:02 pm

Hi Sean,
I am an enthusiastic game developer, and I love nothing but Unity.
I spent a month making 67 maps on tiled for a game, and was planning to use this software only to find out it was only on windows!
I beg you, some way to make a macintosh version!!!
Thanks,
BHDevs

Seanba sez: Hi BHDevs. Tiled2Unity uses C# and has a dependency on MS DLLs so a port is not trivial. However, some folks have reported success with OSX if you check out the comments in this thread.

Seanba sez, part 2: Tiled2UnityLite is now available for use on Mac.

Nanofus December 6, 2015 at 6:26 pm

Hi Sean, and thank you very much. 🙂 This tool has brought me more happiness than any other Unity tool/asset.

However I have a small feature request! I am using this lighting system in my game. It uses polygon 2d colliders, but does not support separate parts in a single polygon collider, or convex polygon colliders.

I have a workaround where I put certain parts of the map in separate layers in Tiled so that they became separate colliders in Unity, but could it be possible to be able to cut a single layer’s collider into separate, non-concave colliders within Tiled2Unity?

Thank you very much!

Seanba sez: Hi Nanofus. I think that’s a good job for a custom importer that takes in a source Polygon2D collider and replaces it with a series of Polygon2D colliders that are convex and without holes. Of course, it’s not trivial, but there’s probably some asset out there than can decompose the complex polygons for you. Just taking a quick look, I’ve found FarseerUnity which claims to have an adequate polygon decomposer in it.

Seanba sez, part 2: Hi again, Nanofus. As of version 1.0.3.0 you can elect to export polygons colliders as a series of convex PolygonCollider2D or the standard PolygonCollider2D which supports holes and concave edges.

Albert December 31, 2015 at 12:45 pm

Assets/Tiled2Unity/Scripts/Runtime/ImportBehaviour.cs(6,18): error CS0234: The type or namespace name `Linq’ does not exist in the namespace `System.Xml’. Are you missing an assembly reference?

That’s the error I get when I export the maps to Unity. All I get is the XML file inside the imported folder and no prefabs. Any ideas?

-A

Seanba sez: I suspect that is due to you choosing Unity Web Player as a platform which Unity has deprecated to the point that Tiled2Unity can no longer support it. Can you try a different platform, like PC/Mac/Linux Standalone? If you must develop for the Unity Web Player you can go with the old version of Tiled2Unity (see the download page) but you’ll be missing some features with that. FWIW, I’ve just put a new version of Tiled2Unity up which will alert users to this limitation from now on.

Wall Penetrator January 4, 2016 at 10:53 am

Hallo! I’d like to ask a question regarding how to export
I followed your steps and it seems that I’m having the same trouble as Emmanuel. It was successfully exported but I’d only get an XML file. Nothing in prefabs, Mesh or in any other folders as well. Even re-importing said file does not change anything.
What should I do?
Oh, and thank you very much for this awesome tool! Have a wonderful day

Seanba sez: The first step is to check the console output window for any errors. Two things that have recently been reported are A) Unity 5.0 is not supported right now (update Unity if you can, but I hope to have workaround for this soon) and B) The Web Player is no longer a viable platform (the latest version of Tiled2Unity should complain in the output)

Schwarz January 9, 2016 at 4:41 am

Is Tiled2Unity compatible to Unity5.0? Or do I have to downgrade/upgrade my Unity3D?

Seanba sez: Hi Schwarz, it turns out Tiled2Unity uses an API introduced with Unity 5.1. Upgrading Unity will fix it. You can also comment out the lines that are not working for you. My next version of Tiled2Unity (probably this weekend, Jan 9th 2016) will take of the compile error with Unity 5.0 as well.

Seanba sez, part 2: The latest version of Tiled2Unity (1.0.2.1) fixes script compile errors with Unity 5.0

Zain Cheema January 12, 2016 at 6:37 pm

Hello there! I have a problem when importing the tiled file into Unity. After specifying where to export to and clicking the big ass export button when Unity tries to import the tiled file it seems to get stuck. I have the same problem on both unity 4 and 5. When I then force quit unity and restart it the same problem occurs where it seems to get stuck when the Tiled file is importing. The tiled file in question is very big and contains a lot of collision data -> I don’t know if this may be the problem. When I try smaller less heavy tiled files they import into unity just fine.
Any help would be appreciated! Thanks!


Seanba sez: Hi Zain, it’s hard to tell without seeing the imported file but “very large” maps tend to be issue even when they do complete importing. It’s always much better to work with smaller maps that are stitched together by some other process. That isn’t unique to Tiled2Unity or Unity, btw, it’s good game development hygine — especially when working with others.

However, I would guess it is your collision data that is slowing down Unity on import. A common source of trouble is when using the Collision Editor in Tiled without turning on “Snap to (Fine) Grid”. You end up with sub-pixel polygons that will not merge well with their neighbors, leading to a real mess. Check that first. You can also email me your imported file and I’ll take a quick look when I can.

Ignacio February 10, 2016 at 9:55 am

Hello Sean! First of all thank you for your tutorial, Really well explained.
I have a question and I feel I’m missing something essential and it’s probably a stupid question but I’ve been searching for days and can’t find an answer.
The thing is, I imported a top down tiled map following the tutorial and all went perfect but now I want to create a Navmesh so I can have some agents patrolling the area. The map is very simple just a ground layer and a walls layer. So I select the tiles layers and mark them as navigation static walkable (the ground) and not walkable (the walls) but for some reason when I try to bake the navmesh nothing happens and I have no idea why.
Is this happening to anybody else? What am I missing?
Thank you!

Seanba sez: Hi Ignacio, I’ve actually never tried to generate navmesh data myself for a 2D game in Unity. The people that do tend to use another plugin they found on the Asset Store and I think that’s because the stock navmesh tools in Unity don’t work (at least well) for 2D projects. Sorry that doesn’t help much but hopefully other users out there can point you in the right direction.

Arjan February 20, 2016 at 8:47 am

Got it to crash:

************** Exception Text **************
System.InvalidOperationException: Sequence contains no elements
at System.Linq.Enumerable.Max[TSource](IEnumerable`1 source)
at Tiled2Unity.TmxMap.ParseTilesetFromImageLayer(XElement elemImageLayer)
( ... rest of stack cut short -- Seanba)

-> I think my map is empty

Seanba sez: Hi Arjan. Turns out this happens when you have a TMX map that uses only Image Layers. The next version of Tiled2Unity will have this fixed. Thanks for letting me know.

Shane March 14, 2016 at 7:56 pm

Hey Sean,

Keep getting this error when exporting to latest Unity. Prefab is also not showing up. Wondering if you have any suggestions.

‘Importing ‘Assets/Tiled2Unity/Imported/First Map.tiled2unity.xml’ but Tiled2Unity files cannot be imported with the WebPlayer[deprecated] platform.
However, You can use Tiled2Unity prefabs imported by another platform.
UnityEngine.Debug:LogWarning(Object)

Hope all is well!

Seanba sez: Unity has stopped supporting the Unity Web Player (it will be removed wholesale with Unity 5.4, thank god). In the meantime you can press CTRL+SHIFT+B in Unity and switch your build platform away from the Web Player. I suggest PC, Mac & Linux.

Christian May 11, 2016 at 8:44 pm

I have an error and its probualy something stupid but here it is,
“Image file not found: F:\roguelikeSheet_transparent.png”
Any help would be amazing, thanks ahead of time 🙂

-Christian J

Nfam0us June 21, 2016 at 12:05 am

I am having the issue that was mentioned earlier, where there’s an xml fille generated. There are, however, no prefabs.

I found this in the Log: Writing face uv coordinates when I noticed that the “clipping” output log had no file listed.

ImportTexture :
will import ‘C:\Users\Bobby\Documents\UnityDataTools\Art\Unsorted\cute_lpc_revised.png’ to C:\Users\Bobby\Documents\UnityDataTools\Projects\DoNE\DoNE\Assets\Tiled2Unity\Assets\Tiled2Unity\Textures\

It’s attempting to import an image from a working directory path to a directory path that doesn’t exist within the Tiled2Unity package.

I’ve tried uninstalling and reinstalling the package, deleting the entire folder its files are in. Doesn’t matter. It keeps trying to pull things to the wrong directories. Even after I manually imported the image into the directory, it still wouldn’t create the prefab.

I’m guessing I did something simple to point it to the wrong place. I’ve been over the directions more than a dozen times, but then my brain’s in pieces from reading switch logs all day (network IT by day, n00b video game dev hobbyist by night).

Any help would be hugely appreciated. Thanks.

Seanba sez: Tiled2Unity was reporting that texture being copied to the wrong diretory and is now fixed.

Hijack June 30, 2016 at 10:53 am

Hi ! I have a problem with Tiled2Unity. When i export my maps, between some tile, there is one pixel space. It happen only on “inside corner” tiles. I double checked my texture, and it’s not coming from this. In Tiled, there is not this problem, it’s only after exporting to unity those space apears. Thanks for yo;ur help !

Seanba sez: Hi Hijack. What are you seeing is seams and it is common when using lights but can also show up under other conditions. The texture sampler sometimes chooses a texel just outside a tile boundary so it ends up rendering a piece of a neighboring tile. This is why you see it on “inside corner” tiles. The best surefire way to fix is to have a 1-pixel “buffer” around your tiles that repeats the pixel that comes before it. This webpage those of good job of explaining it: http://www.firebelly.net/post/114529965784/tile-gaps-using-unity-5-and-tiled2unity

Stephen M July 2, 2016 at 11:06 am

Hi! I made a tiled map called Westland in Tiled. When I get to the part to press the Big Ass Export Button and wait for Unity, I get 2 errors:
‘Assets/Tiles2Unity/Materials/ Westland.mat’ is not a valid asset file name.

And

UnityException” Creating asset at path Assets/Tiled2Unity/Materials Westland.mat failed.

The import progress box is frozen after that and the only way to get rid of it is to exit Unity completely. So I made a new map with a new name, “trial”, but when I try that, i get the same error about Westland, even though I’m not even using that map. Any ideas?

Thank you so much for your help! I’d really appreciate it

Seanba sez: Hi Stephen. The texture being used had a leading whitespace in its filename (i.e. ” Wasteland” instead of “Wasteland”). It turns out in Unity that you can’t name an asset that way. I will look into catching that and warning the user for a future build.

Victor Wu August 4, 2016 at 10:36 am

I have some questions:
1. How can I get the map data ?
For example: I want to implement a SRPG, so I want to know like tile ID of a layer at location (x, y)
Do I have to read the tmx file or you store the tile data somewhere ?

2. Does this util support custom property in TiledMap Editor ?

Thanks for your help.

Seanba sez: Hi Victor.
1) Getting map data can be accomplished a number of ways but takes some work. For an RPG game I recommend using raycasts against colliders where each tile type has its own flavor of a collider. If you need more information than the type of tile your character is on that you’ll need to generate game objects. I talk about both approaches here: http://www.seanba.com/getting-tile-information.html
2) Yes, custom properties are supported but you’ll need to write a custom importer to absorb such properties and “do something” with them. I talk about custom importers here: http://www.seanba.com/megadadadventures.html

Javier Bullrich August 22, 2016 at 9:35 am

Hey, one simple question, what configuration size should I use in Tiled to have the exported map to have every tile the size of 1 Unity Unit? (The same as a simple box)

Thanks!

Gzh August 29, 2016 at 6:46 am

Hello,I make a tiled map , but when I import it to unity.
Tiled map become very big,and main camera viewport rect also too big

Leave a Comment

{ 3 trackbacks }

Previous post:

Next post: