Unity OpenXR输入问题:TryGetFeatureValue始终返回0求助
调试数小时仍未解决:在其他类中调用RightHand.AButtonDown()时始终返回false,已打印所有日志排查但未发现错误,targetDevice输出为UnityEngine.XR.InputDevice且无报错或警告。
调用代码
Debug.Log(RightHand.AButtonDown());
函数实现代码
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.XR; public static class RightHand { private static InputDevice targetDevice; static RightHand() { TryInitialize(); } private static void TryInitialize() { Debug.Log("ran inital"); List<InputDevice> devices = new List<InputDevice>(); InputDeviceCharacteristics rightControllerCharacteristics = InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller; InputDevices.GetDevicesWithCharacteristics(rightControllerCharacteristics, devices); foreach (var item in devices) { Debug.Log("ran log"); Debug.Log(item.name + item.characteristics); } Debug.Log("right controler characteristics" + rightControllerCharacteristics); if (devices.Count > 0) { targetDevice = devices[0]; } Debug.Log(targetDevice); } public static bool AButtonDown() { targetDevice.TryGetFeatureValue(CommonUsages.primaryButton, out bool primaryButtonOut); if (primaryButtonOut) { return true; } else { return false; } } }
排查与解决方向
修正初始化时机问题
静态构造函数执行时XR设备可能还未完成初始化,导致targetDevice绑定无效。改成每次调用方法前检查设备有效性:private static void EnsureDeviceValid() { if (!targetDevice.isValid) { List<InputDevice> devices = new List<InputDevice>(); InputDeviceCharacteristics rightControllerCharacteristics = InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller; InputDevices.GetDevicesWithCharacteristics(rightControllerCharacteristics, devices); if (devices.Count > 0) { targetDevice = devices[0]; } } } public static bool AButtonDown() { EnsureDeviceValid(); targetDevice.TryGetFeatureValue(CommonUsages.primaryButton, out bool primaryButtonOut); return primaryButtonOut; }添加设备有效性检查
在方法里先判断设备是否有效,避免无效设备的调用返回错误结果:public static bool AButtonDown() { if (!targetDevice.isValid) { Debug.LogWarning("右手控制器设备未就绪"); return false; } targetDevice.TryGetFeatureValue(CommonUsages.primaryButton, out bool primaryButtonOut); return primaryButtonOut; }调整设备特性匹配条件
部分控制器的特性可能包含TrackedDevice而非仅Controller,尝试放宽匹配条件:InputDeviceCharacteristics rightControllerCharacteristics = InputDeviceCharacteristics.Right | InputDeviceCharacteristics.TrackedDevice;监听设备连接状态变更
处理运行时设备断开重连的情况,动态更新targetDevice:static RightHand() { InputDevices.deviceConnected += OnDeviceConnected; InputDevices.deviceDisconnected += OnDeviceDisconnected; TryInitialize(); } private static void OnDeviceConnected(InputDevice device) { if ((device.characteristics & (InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller)) == (InputDeviceCharacteristics.Right | InputDeviceCharacteristics.Controller)) { targetDevice = device; } } private static void OnDeviceDisconnected(InputDevice device) { if (targetDevice.name == device.name) { targetDevice = new InputDevice(); } }
内容的提问来源于stack exchange,提问作者Titan1315
相关产品推荐
相关产品推荐

