瀏覽代碼

编辑器和出怪表相连新逻辑

wgl 6 月之前
父節點
當前提交
4cf1bf36f0

+ 127 - 45
ActionTowerDefense/Assets/GameLevelEditor/GameMap/CoreScripts/Editor/GameMapEdPopup.cs

@@ -1,7 +1,10 @@
 using UnityEngine;
 using UnityEditor;
 using UnityEditorInternal;
-
+using System.Collections.Generic;
+using cfg;
+using System;
+using System.IO;
 
 public class GameMapEdPopup : PopupWindowContent
 {
@@ -11,14 +14,17 @@ public class GameMapEdPopup : PopupWindowContent
 	private ReorderableList list;
 	private Rect contentRect;
 	private Vector2 scroll = Vector2.zero;
-
-	private static readonly Vector2 popupSz = new Vector2(200f, 200f);
-	private static readonly GUIContent GC_Head = new GUIContent("Maps");
-	private static readonly GUIContent GC_Add = new GUIContent("+");
-	private static readonly GUIContent GC_Rem = new GUIContent("-");
-
-	public override void OnOpen()
+    private static bool doRepaint;
+    private static readonly Vector2 popupSz = new Vector2(200f, 200f);
+	private static GUIContent GC_Head = new GUIContent("Select");
+	public bool isSelect;
+    private static GUIContent GC_Add = new GUIContent("+");
+    //private static readonly GUIContent GC_Rem = new GUIContent("-");
+
+    public override void OnOpen()
 	{
+		GC_Head = isSelect ? new GUIContent("Select") : new GUIContent("Save");
+		GC_Add = isSelect ? new GUIContent("新建") : new GUIContent("另存");
 		list = new ReorderableList(Asset.maps, typeof(GameMap), true, false, false, false)
 		{
 			elementHeight = EditorGUIUtility.singleLineHeight,
@@ -27,7 +33,7 @@ public class GameMapEdPopup : PopupWindowContent
 			onSelectCallback = SelectMap
 		};
 
-		contentRect = new Rect(0f, 18f, popupSz.x - 20f, Mathf.Max(popupSz.y - 18, EditorGUIUtility.singleLineHeight * Asset.maps.Count + 5));
+		contentRect = new Rect(0f, 25f, popupSz.x - 25f, Mathf.Max(popupSz.y - 25, EditorGUIUtility.singleLineHeight * Asset.maps.Count + 15));
 	}
 
 	public override void OnClose()
@@ -44,12 +50,11 @@ public class GameMapEdPopup : PopupWindowContent
 
 	public override void OnGUI(Rect r)
 	{
-		DrawHeader(new Rect(0, 0, r.width, 18));
-		r.y += 18; r.height -= 18;
+		DrawHeader(new Rect(0, 0, r.width, 25));
+		r.y += 25; r.height -= 25;
 		scroll = GUI.BeginScrollView(r, scroll, contentRect, false, true);
 		list.DoList(r);
 		GUI.EndScrollView();
-
 	}
 
 	private void DrawHeader(Rect r)
@@ -60,38 +65,38 @@ public class GameMapEdPopup : PopupWindowContent
 		}
 
 		GUI.Label(r, GC_Head, EditorStyles.boldLabel);
-		//r.x = r.xMax - 25; r.width = 25;
-		//GUI.enabled = list.index >= 0;
-		//if (GUI.Button(r, GC_Rem, EditorStyles.miniButtonRight))
-		//{
-		//	if (list.index >= 0 && list.index < Asset.maps.Count)
-		//	{
-		//		Undo.RecordObject(Asset, "Remove Game Map");
-		//		int key = list.index;
-		//		Asset.RemoveMapAtIndex(list.index);
-		//		ChangeContentRect();
-		//		if(key == 0)
-  //              {
-		//			OnMapSelected(0);
-  //              }
-  //              else
-  //              {
-		//			OnMapSelected(key - 1);
-		//		}
-				
-		//	}
-		//}
-
-		//GUI.enabled = true;
-		//r.x -= 25;
-		//if (GUI.Button(r, GC_Add, EditorStyles.miniButtonLeft))
-		//{
-		//	Undo.RecordObject(Asset, "Add Game Map");
-		//	Asset.AddMap();
-		//	ChangeContentRect();
-		//	OnMapSelected(Asset.maps.Count - 1);
-		//}
-	}
+        r.x = r.xMax - 90; r.y = 5; r.width = 80;
+        GUI.enabled = list.index >= 0;
+        //if (GUI.Button(r, GC_Rem, EditorStyles.miniButtonRight))
+        //{
+        //    if (list.index >= 0 && list.index < Asset.maps.Count)
+        //    {
+        //        Undo.RecordObject(Asset, "Remove Game Map");
+        //        int key = list.index;
+        //        Asset.RemoveMapAtIndex(list.index);
+        //        ChangeContentRect();
+        //        if (key == 0)
+        //        {
+        //            OnMapSelected(0);
+        //        }
+        //        else
+        //        {
+        //            OnMapSelected(key - 1);
+        //        }
+
+        //    }
+        //}
+
+        //GUI.enabled = true;
+        //r.x -= 25;
+        if (GUI.Button(r, GC_Add, EditorStyles.miniButtonLeft))
+        {
+            //Undo.RecordObject(Asset, "Add Game Map");
+            //Asset.AddMap();
+            //ChangeContentRect();
+            //OnMapSelected(Asset.maps.Count - 1);
+        }
+    }
 
 	private void DrawElement(Rect r, int index, bool isActive, bool isFocused)
 	{
@@ -100,9 +105,86 @@ public class GameMapEdPopup : PopupWindowContent
 
 	private void SelectMap(ReorderableList list)
 	{
-		OnMapSelected(list.index);
+        if (isSelect)
+        {
+			ReloadExcelData(GameMapEditor.enemyExcelPath, list.index);
+			OnMapSelected(list.index);
+        }
+        else
+        {
+			SaveExcelData(GameMapEditor.enemyExcelPath, list.index);
+        }
+		editorWindow.Close();
 	}
 
+	void SaveExcelData(string path, int mapIdx)
+	{
+		List<string> excelWorksheets = ExcelEditor.ReadExcelSheetsInfo(path);
+		GameMap gameMap = GameMapEditor.asset.maps[GameMapEditor.mapIdx];
+
+		if(!ExcelEditor.RenameSheet(path, excelWorksheets[mapIdx], gameMap.showIdent))
+        {
+			return;
+		}
+		ExcelEditor.ModifyExcel(path, gameMap.showIdent, "C6", GameMapEditor.mapSize_w);
+		ExcelEditor.ModifyExcel(path, gameMap.showIdent, "D6", GameMapEditor.mapSize_h);
+
+		Debug.Log($"\"{gameMap.showIdent}\"表保存成功!");
+		Debug.Log("记得运行\"gen_code_json.bat\"更新数据!");
+	}
+
+	public static void ReloadExcelData(string path, int mapIdx)
+	{
+		List<string> excelWorksheets = ExcelEditor.ReadExcelSheetsInfo(path);
+		Tables allCfgData = new Tables(ExcelEditor.Loader);
+		List<SingleCreateEnemyConfig> cfgCreateEnemy = allCfgData.CfgCreateEnemy.DataList;
+		GameMap gameMap = GameMapEditor.asset.maps[mapIdx];
+
+		//导入关卡数据
+		gameMap.showIdent = gameMap.ident;
+		int.TryParse(ExcelEditor.GetCellData(path, excelWorksheets[mapIdx], "C6"), out int width);
+		int.TryParse(ExcelEditor.GetCellData(path, excelWorksheets[mapIdx], "D6"), out int height);
+		gameMap.Resize(width, height);
+
+		//导入波次数据
+		GameMapEditor.currLayer = -1;
+		int mapId = -1;
+		String waveName = "";
+		for (int i = 0; i < cfgCreateEnemy.Count; i++)
+		{
+			if (cfgCreateEnemy[i].WaveName == "这一行不要动")
+			{
+				if(mapId == mapIdx)
+                {
+					break;
+                }
+				mapId++;
+				ArrayUtility.Clear(ref gameMap.layers);
+				continue;
+			}
+			if(mapId == mapIdx)
+            {
+				if (cfgCreateEnemy[i].WaveName != waveName)
+				{
+					waveName = cfgCreateEnemy[i].WaveName;
+					ArrayUtility.Add(ref gameMap.layers, new GameMapLayer());
+					gameMap.InitLayer(gameMap.layers.Length);
+					gameMap.layers[gameMap.layers.Length - 1].name = waveName;
+				}
+			}
+            else
+            {
+				if(i == cfgCreateEnemy.Count - 1)
+                {
+					Debug.LogError("请运行\"gen_code_json.bat\"更新表格数据");
+                }
+            }
+		}
+
+
+		doRepaint = true;
+		Debug.Log($"\"{excelWorksheets[mapIdx]}\"表导入成功!");
+	}
 
 	// ----------------------------------------------------------------------------------------------------------------
 }

+ 33 - 68
ActionTowerDefense/Assets/GameLevelEditor/GameMap/CoreScripts/Editor/GameMapEditor.cs

@@ -27,18 +27,18 @@ public class GameMapEditor : EditorWindow
 	private static Vector2[] scroll = { Vector2.zero, Vector2.zero };
 
 	private bool dragSplitter = false;
-	private bool doRepaint = false;
+	public static bool doRepaint = false;
 
-	private GameMapsAsset asset = null;
+	public static GameMapsAsset asset = null;
 	private GameMapsAsset _setAsset = null;
-	private int mapSize_w = 0;
-	private int mapSize_h = 0;
-	private int mapIdx = -1;
+	public static int mapSize_w = 0;
+	public static int mapSize_h = 0;
+	public static int mapIdx = -1;
 	private int tileIdx = -1;
 	private bool autoTileSelected = false;
 	private float tileDrawSz = 32f;
 	private int dragDropTarget = -1;
-    private int currLayer = -1;
+    public static int currLayer = -1;
     private bool[] layerHidden = new bool[0];
 
 	[NonSerialized] private float tileListH = 1f;
@@ -114,7 +114,7 @@ public class GameMapEditor : EditorWindow
 	private StyleDefs _styles = null;
 	private StyleDefs Styles { get { return _styles ?? (_styles = new StyleDefs()); } }
 
-	private static readonly GUIContent GC_ExcelReload = new GUIContent("-reload-");
+	private static readonly GUIContent GC_ExcelSave = new GUIContent("-save-");
 	private static readonly GUIContent GC_MapSelect = new GUIContent("-select-");
 	private static readonly GUIContent GC_EditorHead = new GUIContent("Editor");
 	private static readonly GUIContent GC_AssetHead = new GUIContent("Asset");
@@ -136,7 +136,7 @@ public class GameMapEditor : EditorWindow
 	private static readonly GUIContent GC_EditAuto = new GUIContent("Setup Auto-tile");
     private static readonly GUIContent GC_Viz = new GUIContent("*", "Toggle layer visblity in editor");
 
-	private static string enemyExcelPath = "Luban/Config/Datas/出怪表.xlsx";
+	public static string enemyExcelPath = "Luban/Config/Datas/出怪表.xlsx";
 
     private GenericMenu addTileMenu = null;
 
@@ -622,14 +622,20 @@ public class GameMapEditor : EditorWindow
 			// map selection button
 			r.height = EditorGUIUtility.singleLineHeight;
 			r.x = r.xMax - 200f; r.width = 100f; r.height = 15f;
-            if (GUI.Button(r, GC_ExcelReload))
+            if (GUI.Button(r, GC_ExcelSave))
             {
-				ReloadExcel(enemyExcelPath);
+				ReloadSheetName(enemyExcelPath);
+				mapsPopup.Asset = asset;
+				mapsPopup.isSelect = false;
+				mapsPopup.OnMapSelected = OnMapSelected;
+				PopupWindow.Show(r, mapsPopup);
 			}
 			r.x = r.xMax; r.width = 100f; r.height = 15f;
 			if (GUI.Button(r, GC_MapSelect))
             {
+				ReloadSheetName(enemyExcelPath);
 				mapsPopup.Asset = asset;
+				mapsPopup.isSelect = true;
 				mapsPopup.OnMapSelected = OnMapSelected;
 				PopupWindow.Show(r, mapsPopup);
 			}
@@ -648,8 +654,8 @@ public class GameMapEditor : EditorWindow
 					EditorGUILayout.BeginHorizontal();
 					{
 						EditorGUILayout.PrefixLabel("Ident");
-						GUILayout.Label(mapIdx.ToString() + " => " + asset.maps[mapIdx].ident);
-						if (GUILayout.Button(GC_rename, EditorStyles.miniButtonRight)) GameMapTextEd.ShowEd("Rename map", "Enter a unique name", asset.maps[mapIdx].ident, OnRenameMap);
+						GUILayout.Label(mapIdx.ToString() + " => " + asset.maps[mapIdx].showIdent);
+						if (GUILayout.Button(GC_rename, EditorStyles.miniButtonRight)) GameMapTextEd.ShowEd("Rename map", "Enter a unique name", asset.maps[mapIdx].showIdent, OnRenameMap);
 						GUILayout.FlexibleSpace();
 					}
 					EditorGUILayout.EndHorizontal();
@@ -665,8 +671,6 @@ public class GameMapEditor : EditorWindow
 							asset.maps[mapIdx].Resize(mapSize_w, mapSize_h);
 							mapSize_w = asset.maps[mapIdx].width;
 							mapSize_h = asset.maps[mapIdx].height;
-							ExcelEditor.ModifyExcel(enemyExcelPath, asset.maps[mapIdx].ident, "C6", mapSize_w);
-							ExcelEditor.ModifyExcel(enemyExcelPath, asset.maps[mapIdx].ident, "D6", mapSize_h);
 						}
 						GUILayout.FlexibleSpace();
 					}
@@ -696,67 +700,34 @@ public class GameMapEditor : EditorWindow
 		EditorGUILayout.EndVertical();
 	}
 
-	private JSONNode Loader(string fileName)
-	{
-		return JSON.Parse(File.ReadAllText("GenerateDatas/json/" + fileName + ".json"));
-	}
-
-	private void ReloadExcel(string path)
+	void ReloadSheetName(string path)
     {
 		List<string> excelWorksheets = ExcelEditor.ReadExcelSheetsInfo(path);
-		Tables allCfgData = new Tables(Loader);
+		Tables allCfgData = new Tables(ExcelEditor.Loader);
 		List<SingleCreateEnemyConfig> cfgCreateEnemy = allCfgData.CfgCreateEnemy.DataList;
-
 		//导入关卡数据
-        if (mapIdx >= excelWorksheets.Count)
-        {
+		if (mapIdx >= excelWorksheets.Count)
+		{
 			mapIdx = 0;
 		}
 		if (asset.maps.Count > excelWorksheets.Count)
-        {
-			for(int i = asset.maps.Count - 1; i>= excelWorksheets.Count; i--)
-            {
+		{
+			for (int i = asset.maps.Count - 1; i >= excelWorksheets.Count; i--)
+			{
 				asset.RemoveMapAtIndex(i);
-            }
-        }
+			}
+		}
 		for (int i = 0; i < excelWorksheets.Count; i++)
 		{
-            if (i >= asset.maps.Count)
-            {
+			if (i >= asset.maps.Count)
+			{
 				asset.AddMap();
-            }
+			}
 			asset.maps[i].ident = excelWorksheets[i];
-			int.TryParse(ExcelEditor.GetCellData(path, excelWorksheets[i], "C6"), out int width);
-			int.TryParse(ExcelEditor.GetCellData(path, excelWorksheets[i], "D6"), out int height);
-			asset.maps[i].Resize(width, height);
-		}
-		mapSize_w = asset.maps[mapIdx].width;
-		mapSize_h = asset.maps[mapIdx].height;
-
-		//导入波次数据
-		currLayer = -1;
-		int mapId = -1;
-		String waveName = "";
-		for(int i = 0; i < cfgCreateEnemy.Count; i++)
-        {
-			if(cfgCreateEnemy[i].WaveName == "这一行不要动")
-            {
-				mapId++;
-				ArrayUtility.Clear(ref asset.maps[mapId].layers);
-				continue;
-            }
-			if(cfgCreateEnemy[i].WaveName != waveName)
-            {
-				waveName = cfgCreateEnemy[i].WaveName;
-                ArrayUtility.Add(ref asset.maps[mapId].layers, new GameMapLayer());
-                asset.maps[mapId].InitLayer(asset.maps[mapId].layers.Length);
-            }
 		}
+	}
 
 
-		doRepaint = true;
-		Debug.Log("出怪表导入成功!");
-	}
 
 
 	private void OnMapSelected(int idx)
@@ -785,12 +756,12 @@ public class GameMapEditor : EditorWindow
 		string s = wiz.text;
 		wiz.Close();
 
-		if (!string.IsNullOrEmpty(s) && s != asset.maps[mapIdx].ident)
+		if (!string.IsNullOrEmpty(s) && s != asset.maps[mapIdx].showIdent)
 		{
 			if (StringIsUnique(asset.maps, s))
 			{
 				Undo.RecordObject(asset, "Rename map");
-				asset.maps[mapIdx].ident = s;
+				asset.maps[mapIdx].showIdent = s;
 			}
 			else
 			{
@@ -821,11 +792,6 @@ public class GameMapEditor : EditorWindow
 				GameMap gameMap = asset.maps[mapIdx];
 				if (GUI.Button(r, GC_rem, EditorStyles.miniButtonRight))
 				{
-
-					ExcelEditor.RemoveExcelRows(enemyExcelPath, gameMap.ident, (ws, row) =>
-					{
-						return ws.Cells[row, 2].Text == gameMap.layers[currLayer].name;
-					});
 					Undo.RecordObject(asset, "Remove Layer");
 					ArrayUtility.RemoveAt(ref gameMap.layers, currLayer);
 
@@ -838,7 +804,6 @@ public class GameMapEditor : EditorWindow
 				if (GUI.Button(r, GC_add, EditorStyles.miniButtonLeft))
 				{
 					int length = gameMap.layers.Length + 1;
-					ExcelEditor.ModifyExcel(enemyExcelPath, gameMap.ident, $"B{length + 8}", length);
 					Undo.RecordObject(asset, "Add Layer");
 					ArrayUtility.Add(ref gameMap.layers, new GameMapLayer());
 					gameMap.InitLayer(length);

+ 0 - 1
ActionTowerDefense/Assets/GameLevelEditor/GameMap/CoreScripts/Editor/GameMapTextEd.cs

@@ -56,7 +56,6 @@ public class GameMapTextEd : EditorWindow
 			if (GUILayout.Button("Accept", GUILayout.Width(80)))
 			{
 				accepted = true;
-				ExcelEditor.RenameSheet("Luban/Config/Datas/出怪表.xlsx", oldText, text);
 			}
 			GUILayout.Space(5);
 			if (GUILayout.Button("Cancel", GUILayout.Width(80))) Close();

+ 1 - 1
ActionTowerDefense/Assets/GameLevelEditor/GameMap/CoreScripts/GameMap.cs

@@ -14,7 +14,7 @@ public class GameMap
 
 	/// <summary> a unique name by which map can be identified </summary>
 	public string ident;
-
+	[HideInInspector] public string showIdent;
 	/// <summary> width of the map (determines how big grid is) </summary>
 	public int width;
 

+ 73 - 18
ActionTowerDefense/Assets/Scripts/ExcelEditor.cs

@@ -4,6 +4,7 @@ using UnityEngine;
 using OfficeOpenXml;
 using System.IO;
 using System;
+using SimpleJSON;
 
 public class ExcelEditor
 {
@@ -26,15 +27,36 @@ public class ExcelEditor
 	}
 
     //修改Sheet名称
-    public static void RenameSheet(string filePath, string oldSheetName, string newSheetName)
+    public static bool RenameSheet(string filePath, string oldSheetName, string newSheetName)
     {
         FileInfo fileInfo = new FileInfo(filePath);
 
         using (ExcelPackage package = new ExcelPackage(fileInfo))
         {
-            ExcelWorksheet worksheet = package.Workbook.Worksheets[oldSheetName];
-            worksheet.Name = newSheetName;
-            package.Save();
+            try
+            {
+                ExcelWorksheet worksheet = package.Workbook.Worksheets[oldSheetName];
+                worksheet.Name = newSheetName;
+                package.Save();
+                Debug.Log($"成功修改Sheet名\"{oldSheetName}\"为\"{newSheetName}\"");
+                return true;
+            }
+            catch (System.InvalidOperationException e)
+            {
+                Debug.LogError($"请关闭Excel后重试");
+                return false;
+            }
+            catch (System.ArgumentException)
+            {
+                Debug.LogError($"Sheet名重复请重试");
+                return false;
+            }
+            catch (System.Exception e)
+            {
+                Debug.Log(e.GetType());
+                Debug.LogException(e);
+                return false;
+            }
         }
     }
 
@@ -52,21 +74,35 @@ public class ExcelEditor
     }
 
     //修改excel文件
-    public static void ModifyExcel(string filePath, string sheetMame, string cellId, int newData)
+    public static bool ModifyExcel(string filePath, string sheetMame, string cellId, int newData)
     {
         FileInfo fileInfo = new FileInfo(filePath);
 
 
         using (ExcelPackage package = new ExcelPackage(fileInfo))
         {
-            ExcelWorksheet worksheet = package.Workbook.Worksheets[sheetMame];
-            worksheet.Cells[cellId].Value = newData; // 通过单元格地址
-            package.Save();
+            try
+            {
+                ExcelWorksheet worksheet = package.Workbook.Worksheets[sheetMame];
+                worksheet.Cells[cellId].Value = newData; // 通过单元格地址
+                package.Save();
+                return true;
+            }
+            catch (System.InvalidOperationException e)
+            {
+                Debug.LogError($"请关闭Excel后重试");
+                return false;
+            }
+            catch (System.Exception e)
+            {
+                Debug.LogException(e);
+                return false;
+            }
         }
     }
 
     //删除符合条件的几行数据
-    public static void RemoveExcelRows(string filePath, string sheetMame, Func<ExcelWorksheet, int, bool> rowCondition)
+    public static bool RemoveExcelRows(string filePath, string sheetMame, Func<ExcelWorksheet, int, bool> rowCondition)
     {
         FileInfo fileInfo = new FileInfo(filePath);
 
@@ -76,21 +112,40 @@ public class ExcelEditor
             int rowCount = worksheet.Dimension.Rows;
             int deletedRows = 0;
 
-            // 从最后一行开始遍历,避免索引问题
-            for (int row = rowCount; row >= 1; row--)
+            try
             {
-                if (rowCondition(worksheet, row))
+                // 从最后一行开始遍历,避免索引问题
+                for (int row = rowCount; row >= 1; row--)
                 {
-                    worksheet.DeleteRow(row);
-                    deletedRows++;
+                    if (rowCondition(worksheet, row))
+                    {
+                        worksheet.DeleteRow(row);
+                        deletedRows++;
+                    }
                 }
-            }
 
-            if (deletedRows > 0)
+                if (deletedRows > 0)
+                {
+                    package.Save();
+                }
+                return true;
+            }
+            catch (System.InvalidOperationException e)
             {
-                package.Save();
-                Debug.Log($"已删除 {deletedRows} 行");
+                Debug.LogError($"请关闭Excel后重试");
+                return false;
+            }
+            catch (System.Exception e)
+            {
+                Debug.LogException(e);
+                return false;
             }
         }
     }
+
+    //读取excel的jason参数
+    public static JSONNode Loader(string fileName)
+    {
+        return JSON.Parse(File.ReadAllText("GenerateDatas/json/" + fileName + ".json"));
+    }
 }