Unity中如何在控制台面板查看数组或列表的打印内容
Unity 默认直接调用 Debug.Log() 传入数组(Array)或列表(List)时,只会输出集合的类型名称(比如System.Int32[]、System.Collections.Generic.List'1[System.Int32]),无法直接看到内部存储的元素。要达成 Debug.Log(array) -> [1,2,3,4] 的打印效果,可参考以下几种可行方案:
通用扩展方法方案(最推荐,适配所有集合类型)
写一个通用的静态扩展类,封装集合的字符串格式化逻辑,支持所有实现了IEnumerable接口的集合类型,无侵入、调用方便。
实现代码如下:using System.Collections.Generic; using System.Text; public static class CollectionDebugExtension { public static string ToLogStr<T>(this IEnumerable<T> collection) { if (collection == null) return "[null]"; StringBuilder sb = new StringBuilder("["); bool firstItem = true; foreach (var item in collection) { if (!firstItem) sb.Append(','); sb.Append(item?.ToString() ?? "null"); firstItem = false; } sb.Append(']'); return sb.ToString(); } }调用方式非常简单,直接在集合变量后调用扩展方法即可:
int[] intArray = new int[]{1,2,3,4}; List<string> strList = new List<string>{"Unity","C#","Debug"}; Debug.Log(intArray.ToLogStr()); // 控制台输出 [1,2,3,4] Debug.Log(strList.ToLogStr()); // 控制台输出 [Unity,C#,Debug]自定义类型重写ToString方案
如果数组/List存储的是自定义的类、结构体,可以给自定义类型重写ToString()方法,定义单条数据的输出格式,再配合上述扩展方法,就能打印出结构化的集合内容。示例:public class ItemInfo { public int itemId; public int count; public override string ToString() { return $"{{itemId:{itemId}, count:{count}}}"; } } // 对应数组打印效果:[{itemId:101, count:2},{itemId:102, count:5}]Inspector面板直接查看方案(适合调试时浏览大量数据)
如果不需要把集合内容输出到日志文本,只是运行时调试查看内容,不需要额外写打印代码:给存储数组/List的字段加上[SerializeField]属性,即使是私有字段,运行时也可以直接在Inspector面板展开集合,查看所有元素的具体值,比打印日志更适合查看大容量集合。
注意:C# 不支持对内置的数组、List
类型重写ToString方法,因此不存在完全不做封装、直接调用 Debug.Log(array)就输出格式化元素列表的原生方案,必须通过扩展方法或者自定义封装的日志接口实现该效果。
内容的提问来源于stack exchange,提问作者222 2

