チラ裏Unity

主にUnityについての備忘録ですが誰か様の為になれば

Unityで位置情報を取得

Unityの準備

  1. http://docs.unity3d.com/ScriptReference/LocationService.Start.htmlサンプルソースを使います
  2. C#の場合、そのまま使うと以下のエラーになるので

    error CS0126: An object of a type convertible to `bool' is required for the return statement

    文中のreturn;yield break;に修正
    using UnityEngine;
    using System.Collections;

    public class GPSLoader : MonoBehaviour {
        IEnumerator Start() {
            if (!Input.location.isEnabledByUser) {
                yield break;
            }
            Input.location.Start();
            int maxWait =  120;
            while (Input.location.status == LocationServiceStatus.Initializing && maxWait > 0) {
                yield return new WaitForSeconds(1);
                maxWait--;
            }
            if (maxWait < 1) {
                print("Timed out");
                yield break;
            }
            if (Input.location.status == LocationServiceStatus.Failed) {
                print("Unable to determine device location");
                yield break;
            } else {
                print("Location: " + 
                      Input.location.lastData.latitude + " " + 
                      Input.location.lastData.longitude + " " + 
                      Input.location.lastData.altitude + " " + 
                      Input.location.lastData.horizontalAccuracy + " " + 
                      Input.location.lastData.timestamp);
            }
            Input.location.Stop();
        }
    }

  3. 適当なGameObjectにアタッチ

 

Android実機の準備

(機種によってメニューの項目名が異なるかもしれません)

  1. 設定 > 位置情報サービス > GPS機能の使用にチェック
  2. 設定 > 位置情報サービス > Googleの位置情報にチェック

 

iPhone実機の準備

iOSのバージョンによって項目名が異なるかもしれません)

  1. 設定 > プライバシー > 位置情報サービス にチェック
  2. このアプリに対して位置情報の利用を許可
    (アプリ初回起動時に確認ダイアログが表示される)

 

実機で動作確認

 

補足