Hello Unity developers,
I’m using #Unity-2022-3-LTS for development on Android devices (Pixel 3 with Android 12 and Pixel 5 with Android 13). Currently, I’m facing an issue where Input.compass.trueHeading and Input.compass.magneticHeading return the same values.
Here is the script I’m using:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Location : MonoBehaviour
{
public static Location Instance { set; get; }
public float latitude;
public float longitude;
public float altitude;
public int gps_count = 0;
public string message;
public float trueHeading;
public float magneticHeading;
public float compassAccuracy;
public Quaternion gyroAttitude;
public Vector3 eulerAngles;
public float declination;
private void Start()
{
Instance = this;
DontDestroyOnLoad(gameObject);
Input.gyro.enabled = false;
Input.compass.enabled = false;
Input.gyro.enabled = true;
StartCoroutine(StartLocationService());
Input.compass.enabled = true;
}
private IEnumerator StartLocationService()
{
// First, check if user has location service enabled
if (!Input.location.isEnabledByUser)
{
Debug.Log("GPS not enabled");
message = "GPS not enabled";
yield break;
}
// Start service before querying location
Input.location.Start();
// Wait until service initializes
int maxWait = 20;
while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
{
yield return new WaitForSeconds(1);
maxWait--;
}
// Service didn't initialize in 20 seconds
if (maxWait <= 0)
{
Debug.Log("Timed out");
message = "Timed out";
yield break;
}
// Connection has failed
if (Input.location.status == LocationServiceStatus.Failed)
{
Debug.Log("Unable to determine device location");
message = "Unable to determine device location";
yield break;
}
// Set locational information
while (true)
{
latitude = Input.location.lastData.latitude;
longitude = Input.location.lastData.longitude;
altitude = Input.location.lastData.altitude;
gyroAttitude = new Quaternion(-Input.gyro.attitude.x, -Input.gyro.attitude.y, -Input.gyro.attitude.z, Input.gyro.attitude.w);
eulerAngles = gyroAttitude.eulerAngles;
trueHeading = Input.compass.trueHeading;
magneticHeading = Input.compass.magneticHeading;
compassAccuracy = Input.compass.headingAccuracy;
gps_count++;
yield return new WaitForSeconds(1);
}
}
}
Details of the issue are as follows:
- I’ve confirmed that GPS is successfully enabled.
- Gyro sensor and compass are also enabled without any issues.
- However,
Input.compass.trueHeadingandInput.compass.magneticHeadingvalues are the same, and I’m not getting the expected behavior.
If anyone has encountered a similar issue or knows of a solution, could you please provide some advice?
I appreciate your help. Thank you.