Unity中如何打印Touch/Input类全部属性值?排查NaN异常
如何在Unity中完整打印Touch对象的所有内部值
Unity的Touch类默认ToString()只会输出简略信息,要获取所有内部值来排查NaN问题,你可以用以下两种实用方法:
方法1:手动拼接所有公开字段
直接枚举Touch的所有公开属性,拼接成详细日志,适合快速定位问题:
void Update() { if (Input.touchCount > 0) { Touch theTouch = Input.GetTouch(0); string touchDetails = $"Touch 详情:\n" + $"FingerId: {theTouch.fingerId}\n" + $"Position: {theTouch.position}\n" + $"RawPosition: {theTouch.rawPosition}\n" + $"DeltaPosition: {theTouch.deltaPosition}\n" + $"DeltaTime: {theTouch.deltaTime}\n" + $"TapCount: {theTouch.tapCount}\n" + $"Phase: {theTouch.phase}\n" + $"Pressure: {theTouch.pressure}\n" + $"MaximumPressure: {theTouch.maximumPressure}\n" + $"Radius: {theTouch.radius}\n" + $"RadiusVariance: {theTouch.radiusVariance}"; Debug.Log(touchDetails); } }
这样就能把Touch的所有数值型、枚举型属性都输出到日志里,方便你检查哪个字段出现了NaN(重点关注位置、压力这类浮点字段)。
方法2:用反射自动遍历字段
如果不想手动写所有字段,可以用反射工具类自动获取对象的所有公共成员,通用性更强:
using System.Reflection; using System.Text; public static class ObjectLogger { public static string GetFullObjectInfo(object target) { if (target == null) return "空对象"; Type objType = target.GetType(); StringBuilder logBuilder = new StringBuilder(); logBuilder.AppendLine($"{objType.Name} 完整信息:"); // 遍历所有公共字段 foreach (FieldInfo field in objType.GetFields(BindingFlags.Public | BindingFlags.Instance)) { object value = field.GetValue(target); logBuilder.AppendLine($"{field.Name}: {value}"); } // 遍历所有可读公共属性 foreach (PropertyInfo prop in objType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { if (prop.CanRead) { object value = prop.GetValue(target); logBuilder.AppendLine($"{prop.Name}: {value}"); } } return logBuilder.ToString(); } } // 使用示例 void Update() { if (Input.touchCount > 0) { Touch theTouch = Input.GetTouch(0); Debug.Log(ObjectLogger.GetFullObjectInfo(theTouch)); } }
这个工具类可以复用在任何Unity对象上,自动打印所有公共字段和属性值,不用重复编写拼接代码。
NaN排查额外提示
针对NaN问题,你可以在打印时直接加异常判断,快速定位问题字段:
Touch theTouch = Input.GetTouch(0); if (float.IsNaN(theTouch.position.x) || float.IsNaN(theTouch.position.y)) { Debug.LogError("触摸位置出现NaN值!"); }
内容的提问来源于stack exchange,提问作者flix
相关产品推荐
相关产品推荐

