通过Mono Debugger Wire Protocol获取Unity静态属性值遇异常求助
我尝试通过Mono Debugger Wire Protocol控制Unity Editor,想要获取UnityEditor.SceneHierarchyWindow的public static属性lastInteractedHierarchyWindow的值,编写了以下代码:
using VirtualMachine = Mono.Debugger.Soft.VirtualMachine; // vm points to the virtual machine of the Unity Editor internal void SomeWhat(VirtualMachine vm) { var hierarchyWindow = vm.GetTypes("UnityEditor.SceneHierarchyWindow", false)!.Single()!; var prev = hierarchyWindow.GetMethod("SelectPrevious")!; var latestWindow = hierarchyWindow .GetProperty("lastInteractedHierarchyWindow") .GetGetMethod(false) .Evaluate(null, new Value[] { }); prev.Evaluate(latestWindow, new Value[] {}); }
运行时抛出System.NotSupportedException异常:
Unhandled exception. System.NotSupportedException: Specified method is not supported. at Mono.Debugger.Soft.ILInterpreter.Evaluate(Value this_val, Value[] args) in $PROJECT/deps/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/ILInterpreter.cs:line 43 at Mono.Debugger.Soft.MethodMirror.Evaluate(Value this_val, Value[] args) in $PROJECT/deps/debugger-libs/Mono.Debugger.Soft/Mono.Debugger.Soft/MethodMirror.cs:line 466 at Blah.SomeWhat(VirtualMachine vm) in $PROJECT/$PROJECT_NAME/SandBox/Lib.cs:line $LINE
环境说明:使用Unity Editor 2019.4.31f1,mono/debugger-libs版本为6fcc6d78446b1fffac12f597099cc3d78dd74ca6。
解决思路
替换静态方法调用方式:Mono Debugger Soft的
MethodMirror.Evaluate对静态方法传null作为this_val存在兼容性问题,改用Invoke方法替代Evaluate,静态方法调用时this_val传null是合法的:var getLastWindowMethod = hierarchyWindow .GetProperty("lastInteractedHierarchyWindow") .GetGetMethod(false); var latestWindow = getLastWindowMethod.Invoke(null, new Value[] { });验证方法静态性:通过
getLastWindowMethod.IsStatic确认获取的是静态方法,避免因误取实例方法导致的错误。规避IL解释器限制:
Evaluate依赖IL解释器执行,部分Unity编译的方法不支持该模式;Invoke直接在目标VM中执行方法,兼容性更强。确认访问权限:确保
lastInteractedHierarchyWindow的getter为public static(Unity 2019.4中该属性确实符合),同时确认调试器已正确附加到Unity Editor进程并拥有访问权限。
内容的提问来源于stack exchange,提问作者user-id-14900042

