本文介绍的是Unity官方的2d地编工具如何导出地图数据
下面开始我们的教程
一、添加两个脚本
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Tilemaps; [RequireComponent(typeof(Tilemap))] public class TilemapBehaviour : MonoBehaviour { private Tilemap tileMap; public Tilemap Tilemap { get { if (tileMap == null) tileMap = GetComponent<Tilemap>(); return tileMap; } } public BoundsInt area; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEngine.Tilemaps; using System.IO; [CustomEditor(typeof(TilemapBehaviour))] [CanEditMultipleObjects] public class TilemapInspector : Editor { private TilemapBehaviour tilemapBehaviour; public override void OnInspectorGUI() { tilemapBehaviour = (TilemapBehaviour)target; base.OnInspectorGUI(); if (GUILayout.Button("导出地图")) { ExportMap(); } if (GUILayout.Button("清除地图")) { if (EditorUtility.DisplayDialog("提示", "确定要清除地图吗?", "确定", "取消")) ClearMap(); } } public void ExportMap() { TileBase[] tileArray = tilemapBehaviour.Tilemap.GetTilesBlock(tilemapBehaviour.area); Debug.Log(string.Format("Tilemap:{0} 准备导出地图数据", tilemapBehaviour.Tilemap.name)); int tilecount = 0; Dictionary<string, string> data = new Dictionary<string, string>(); for (int i = tilemapBehaviour.area.xMin; i < tilemapBehaviour.area.xMax; i++) { for (int j = tilemapBehaviour.area.yMin; j < tilemapBehaviour.area.yMax; j++) { Vector3Int tempVec = new Vector3Int(i, j, 0); if (tilemapBehaviour.Tilemap.GetTile(tempVec) == null) continue; Debug.Log(string.Format("位置:{0} Tile:{1}", tempVec.ToString(), tilemapBehaviour.Tilemap.GetTile(tempVec).ToString())); data.Add(i + "_" + j, tilemapBehaviour.Tilemap.GetTile(tempVec).name); tilecount++; } } string jsonData = LitJson.JsonMapper.ToJson(data); ExportMap(jsonData, tilemapBehaviour.Tilemap.name); Debug.Log(string.Format("Tilemap:{0} 总共Tile数量:{1}", tilemapBehaviour.Tilemap.name, tilecount.ToString())); } public void ExportMap(string data, string mapName) { string fullPath = EditorUtility.SaveFilePanel("保存地图文件", Application.dataPath, mapName, "json"); if (string.IsNullOrEmpty(fullPath)) return; TextWriter tw = new StreamWriter(fullPath, false); tw.Write(data); tw.Close(); Debug.Log("导出地图完成 path:" + fullPath); AssetDatabase.SaveAssets(); AssetDatabase.Refresh(); } public void ClearMap() { tilemapBehaviour.Tilemap.ClearAllTiles(); } } |
二、在Tilemap物体上挂载“TilemapBehaviour.cs”
三、手动填入Area值
四、点击导出即可
导出的地图数据样例:
1 |
{"3_12":"gray","4_9":"gray","6_11":"gray","8_15":"gray 1","8_16":"gray 1","11_16":"gray"} |
这里只示范下简单的导出数据,具体数据格式可以自己根据项目需求定义
GitHub下载地址:
https://github.com/654306663/TilemapExporter
- 本文固定链接: http://www.u3d8.com/?p=2285
- 转载请注明: 网虫虫 在 u3d8.com 发表过