简体   繁体   English

在 Unity 中触发接近传感器时遇到问题

[英]Having issues triggering the proximity sensor in Unity

I am trying to use the proximity sensor in my phone using unity remote.我正在尝试使用统一遥控器在我的手机中使用接近传感器。 I tried to follow this Documentation我试图遵循这个文档

The input system is working fine.输入系统工作正常。 I have everything installed and I've imported all the samples,also unity remote is working and I've tested the sensor on my android device using Sensor Test App.我已经安装了所有东西并且我已经导入了所有示例,Unity Remote 也在工作,我已经使用 Sensor Test App 在我的 android 设备上测试了传感器。

/ All I want to do is trigger this script and test if it's working or not. /我想要做的就是触发这个脚本并测试它是否工作。 I could not attach it to a gameObject because it is not derived from MonoBehaviour.我无法将它附加到游戏对象,因为它不是从 MonoBehaviour 派生的。 / /

EDIT : I've changed the script to MonoBehaviour.before, It was derived from Sensor编辑:我已将脚本更改为 MonoBehaviour.before,它源自 Sensor

This is my new sensor script :这是我的新传感器脚本:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

public class Prox : MonoBehaviour
{
    public ProximitySensor proximity;

private void Start()
{

    if (ProximitySensor.current != null)
    {
        var _ProximitySensor = ProximitySensor.current;
        InputSystem.EnableDevice(_ProximitySensor);
        Debug.Log("proximity sensor is working");
    }
    Debug.Log("proximity error");
}
void Update()
{

    if (proximity != null)
    {
      //  InputSystem.EnableDevice(proximity);
        var _ProximitySensor = ProximitySensor.current;
        Debug.Log(_ProximitySensor);
        var _dist = _ProximitySensor.distance;
        Debug.Log(_dist);
    }
    else
    {
       Debug.Log("null");
    }
}
}

The output from the console is always returning "proximity error" this means I'm getting null value from ProximitySensor.current.控制台的输出总是返回“接近错误”,这意味着我从 ProximitySensor.current 获取空值。 What I want to do is move a gameObject when the proximity sensor is triggered (the user is holding the phone to their ear).我想要做的是在触发接近传感器时移动游戏对象(用户将手机放在耳边)。

Any help would be appreciated任何帮助,将不胜感激

You are getting "proximity error" because the code that displays it is in the Start() function and it will always be executed.您会收到“邻近错误”,因为显示它的代码位于 Start() 函数中,并且它将始终被执行。 You have to write:你必须写:

private void Start()
{
    if (ProximitySensor.current != null)
    {
        var _ProximitySensor = ProximitySensor.current;
        InputSystem.EnableDevice(_ProximitySensor);
        Debug.Log("proximity sensor is working");
    }
    else
    {
        Debug.Log("proximity error");
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM