using UnityEngine; using System; // 确保你已经通过 Package Manager 或手动导入了 Newtonsoft.Json using Newtonsoft.Json; using UnityEngine.Tilemaps; public class RuleTileInspector : MonoBehaviour { [Tooltip("将一个 RuleTile 资产拖拽到这里以检查其内容。")] public RuleTile ruleTile; // 使用 ContextMenu 属性在 Inspector 组件右键菜单或齿轮菜单中添加按钮 [ContextMenu("打印 RuleTile 内容 (JSON)")] private void PrintRuleTileContentAsJson() { if (ruleTile == null) { Debug.LogWarning("RuleTile 字段未分配,请拖拽一个 RuleTile 资产。", this); return; } // 创建序列化设置 var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore, // 忽略 null 值属性,防止 UnassignedReferenceException ReferenceLoopHandling = ReferenceLoopHandling.Ignore, // 忽略循环引用(作为安全网) Formatting = Formatting.Indented, // 格式化输出,可读性更好 // 应用自定义的 ContractResolver 来处理 Unity 值类型属性 ContractResolver = new UnityPropertyContractResolver(), // 应用自定义的 Converter 来处理 UnityEngine.Object 引用类型 Converters = { new UnityObjectConverter() } }; try { // 序列化 ruleTile.m_TilingRules 列表 string json = JsonConvert.SerializeObject(ruleTile.m_TilingRules, settings); Debug.Log("Serialized RuleTile Tiling Rules:\n" + json); } catch (JsonSerializationException ex) { Debug.LogError($"JSON Serialization Error: {ex.Message}\nPath: {ex.Path}\nStackTrace: {ex.StackTrace}"); if (ex.InnerException != null) { Debug.LogError( $"Inner Exception: {ex.InnerException.Message}\nInner StackTrace: {ex.InnerException.StackTrace}"); } } catch (Exception ex) { Debug.LogError($"Unexpected Error during serialization: {ex.Message}\nStackTrace: {ex.StackTrace}"); } } }