You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity使用Unity Remote调用安卓手机接近传感器触发失败问题求助

问题解决步骤

  • 第一步:修正原代码的逻辑错误
    原Start方法中Debug.Log("proximity error")没有放在else分支,无论传感器是否存在都会输出该日志,首先修正这个逻辑避免误判。
  • 第二步:不要用Unity Remote测试该功能
    Unity Remote仅支持转发加速度计、陀螺仪、触摸等常用输入,接近传感器默认不会同步到Editor端,这是ProximitySensor.current返回空的核心原因,直接打包APK到真机运行测试即可。
  • 第三步:补充权限和Input System配置
    1. 打开Edit > Project Settings > Player > Android > Permissions,勾选ACCESS_FINE_LOCATION(部分安卓机型调用接近传感器需要该权限)
    2. 打开Edit > Project Settings > Input System Package,确认Proximity Sensor已勾选启用
  • 第四步:使用修正后的功能代码
using UnityEngine;
using UnityEngine.InputSystem;

public class Prox : MonoBehaviour
{
    // Inspector面板赋值需要移动的目标对象
    public GameObject targetObject;
    // 接近触发阈值,单位米,通常安卓设备触发距离为0~5cm,可按需调整
    public float triggerDistance = 0.05f;
    
    private ProximitySensor _proxSensor;

    private void Start()
    {
        _proxSensor = ProximitySensor.current;
        if (_proxSensor != null)
        {
            InputSystem.EnableDevice(_proxSensor);
            Debug.Log("接近传感器启用成功");
        }
        else
        {
            Debug.Log("未检测到接近传感器");
        }
    }

    private void Update()
    {
        if (_proxSensor == null || !_proxSensor.enabled) return;
        
        float currentDist = _proxSensor.distance.ReadValue();
        // 距离小于阈值时触发移动,此处可自定义你的移动逻辑
        if (currentDist < triggerDistance)
        {
            // 示例:目标沿Y轴每秒向上移动1单位
            targetObject.transform.Translate(Vector3.up * Time.deltaTime);
        }
    }

    private void OnDestroy()
    {
        // 退出时禁用传感器降低功耗
        if (_proxSensor != null && _proxSensor.enabled)
        {
            InputSystem.DisableDevice(_proxSensor);
        }
    }
}

内容的提问来源于stack exchange,提问作者Selim

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 11:15:04