2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Unity】コンパスの値がとれない

Last updated at Posted at 2019-09-21

オフラインで使用できるARKitのiOSアプリを作ろうとUnity 2019.1.14fでコンパスを使用したのですが、なぜかコンパスの値を取得できない問題が起こったため、その原因と解決策を記します。

UnityEngine.Compass

Unityには端末のコンパスを使用するための関数 Input.compass が用意されています。

Unity コンパスリファレンス

今回はデバイスのコンパスの値をとる関数 Input.compass.magneticHeading を使いました。

通常の使い方は以下の通りです。

using UnityEngine;

public class Example : MonoBehaviour
{
    void Start()
    {
        Input.compass.enabled = true; //コンパス有効化
    }
    void Update()
    {
        // Orient an object to point to magnetic north.
        transform.rotation = Quaternion.Euler(0, -Input.compass.magneticHeading, 0);
    }
}

問題発生

しかし、上のようなコードで実行すると Input.compass.magneticHeading が値を取得してくれませんでした。

原因を探しているとvoid Start()内で Input.location.Start() を呼ぶと正常に動作することがわかりました。

似たような関数の Input.compass.trueHeading(北極点からの方角)では位置情報を使用するのですが、 Input.compass.magneticHeading では位置情報を必要としないため、なぜ位置情報を有効にしなければならないのかは謎です。(実際ネット上の記事やAndroidでは有効にしなくても取得できていた)

これでは、位置情報を取得する関数であるため通信が必要となってしまいます。位置情報のパーミッションをOFFにしても正常に値が取得できたので結局位置データは使ってないようです。

結局 Input.location.Start() を呼んで、位置情報のパーミッションを切ることでオフライン対応しました。

using UnityEngine;

public class Example : MonoBehaviour
{
    void Start()
    {
        Input.compass.enabled = true;
        Input.location.Start(); //位置情報有効化
    }
    void Update()
    {
        // Orient an object to point to magnetic north.
        transform.rotation = Quaternion.Euler(0, -Input.compass.magneticHeading, 0);
    }
}
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?