Search Unity

  1. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Question Problem using LinearAccelerationSensor

Discussion in 'Input System' started by Innarq, Nov 29, 2023.

  1. Innarq

    Innarq

    Joined:
    Oct 13, 2021
    Posts:
    1
    I want to get user device's (mobile phone's) acceleration without gravity.
    I found this documentation bout new input system, and LinearAccelerationSensor seems like it's what I need but I don't get how to use it.

    Here's code I've tried to use:
    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.InputSystem;
    3. using TMPro;
    4.  
    5. public class AccelerometerDisplay : MonoBehaviour
    6. {
    7.     public TextMeshProUGUI debugText;
    8.     private LinearAccelerationSensor linearAccelerationSensor;
    9.     Vector3 linearAcceleration;
    10.  
    11.     void Update()
    12.     {
    13.         if (linearAccelerationSensor == null)
    14.         {
    15.             // Attempt to get the LinearAccelerationSensor
    16.             linearAccelerationSensor = InputSystem.GetDevice<LinearAccelerationSensor>();
    17.             if (linearAccelerationSensor != null)
    18.             {
    19.                 debugText.text = "Linear Acceleration Sensor found!";
    20.             }
    21.             else
    22.             {
    23.                 debugText.text = "Linear Acceleration Sensor not found.";
    24.                 return;
    25.             }
    26.         }
    27.  
    28.         linearAcceleration = linearAccelerationSensor.acceleration.ReadValue();
    29.  
    30.         debugText.text = linearAcceleration.x + " " + linearAcceleration.y + " " + linearAcceleration.z ;
    31.     }
    32. }
    Tried on both unity Play and built on my mobile phone and on both it always shows "Linear Acceleration Sensor not found.". What I'm doing wrong?