Hololens2+Unity2021中SpatialCoordinateSystem类型转换异常求助
解决Hololens 2 + Unity 2021.3中SpatialCoordinateSystem类型转换异常的思路
问题本质
你遇到的是同名类型来自不同程序集导致的加载冲突——虽然输出显示类型名称一致,但实际是两个不同程序集里的SpatialCoordinateSystem,因此无法转换。
具体解决步骤
明确命名空间与类型归属
移除旧的UnityEngine.XR.WindowsMR相关using语句,避免命名空间冲突。显式指定类型的完整命名空间,消除歧义:// 直接使用OpenXR封装的类型 var coordinateSystem = PerceptionInterop.GetSceneCoordinateSystem(Pose.identity); Microsoft.MixedReality.OpenXR.SpatialCoordinateSystem unityCs = coordinateSystem as Microsoft.MixedReality.OpenXR.SpatialCoordinateSystem; // 如果需要转换为WinRT原生类型,用OpenXR的工具方法 Windows.Perception.Spatial.SpatialCoordinateSystem winrtCs = PerceptionInterop.UnwrapSpatialCoordinateSystem(coordinateSystem);清理重复的DLL与插件
- 打开Package Manager,卸载旧的
Windows MR XR Plugin,只保留Microsoft Mixed Reality OpenXR Plugin,确保版本与Unity 2021.3兼容(推荐1.7.x及以上)。 - 检查项目
Assets/Plugins/WSA目录,删除所有重复的Windows.Perception.Spatial.dll或遗留的旧版DLL,防止Unity加载多个版本的同类型。
- 打开Package Manager,卸载旧的
调整编译配置
- 确认Player Settings → Other Settings中的Api Compatibility Level设为
.NET 4.x Equivalent或.NET Standard 2.1。 - 开启Allow 'unsafe' Code选项,部分OpenXR交互依赖此配置。
- 确保Scripting Runtime Version为
.NET 4.x Equivalent。
- 确认Player Settings → Other Settings中的Api Compatibility Level设为
清理缓存并重建项目
- 删除项目根目录的
Library文件夹,重启Unity让其重新生成依赖缓存。 - 右键Assets目录选择Reimport All,确保所有脚本和DLL被正确重新导入。
- 删除项目根目录的
验证程序集来源
添加日志查看类型所属的程序集,确认是否存在冲突:var coordinateSystem = PerceptionInterop.GetSceneCoordinateSystem(Pose.identity); Debug.Log("Runtime type assembly: " + coordinateSystem.GetType().Assembly.FullName); Debug.Log("Target type assembly: " + typeof(Windows.Perception.Spatial.SpatialCoordinateSystem).Assembly.FullName);如果两个程序集的名称、版本不一致,说明存在冲突,需要移除其中一个对应的DLL或插件。
内容的提问来源于stack exchange,提问作者Phippe
相关产品推荐
相关产品推荐

