Having issues triggering the proximity sensor in Unity

526 Views Asked by At

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.

/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./

EDIT : I've changed the script to MonoBehaviour.before, It was derived from 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. 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

1

There are 1 best solutions below

1
A Simple Developer On BEST ANSWER

You are getting "proximity error" because the code that displays it is in the Start() function and it will always be executed. 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");
    }
}