zaport-ARTech

The technical problem I tackled was figuring out how to use the phone’s GPS in my Unity app. I used a number of online sources/tutorials to work through this. I credit N3K EN for provide a significant amount of support on this project (https://www.youtube.com/watch?v=g04jaC-Tpn0). To use the GPS data from a phone, I needed to write a script to do a couple of things. The first was to ensure the phone allows Unity to access that data. If the phone is set up to deny this location service data, the app will not work. Next, I needed to find the latitude and longitude values of the position. Finally, I wrote a script to update the output position as I move around.

GPS Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class GPS : MonoBehaviour {
 
	public static GPS Instance {set; get;}
 
	public float latitude;
	public float longitude;
 
	private void Start()
	{
		Instance = this;
		DontDestroyOnLoad (gameObject);
		StartCoroutine (StartLocationService ());
	}
 
	private IEnumerator StartLocationService()
	{
		if(!Input.location.isEnabledByUser)
		{
			Debug.Log ("Enable the GPS!!! :)");
			yield break;
		}
 
		Input.location.Start();
		int maxWait = 20;
		while(Input.location.status == LocationServiceStatus.Initializing && maxWait > 0)
		{
			yield return new WaitForSeconds(1);
			maxWait--;
		}
 
		if(maxWait<= 0)
		{
			Debug.Log("Out of Time...");
			yield break;
		}
 
		if (Input.location.status == LocationServiceStatus.Failed)
		{
			Debug.Log("Can't determine ya location");
			yield break;
		}
 
		latitude = Input.location.lastData.latitude;
		longitude = Input.location.lastData.longitude;
 
		yield break;
 
	}
}

Update GPS Text Code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
 
public class UpdateGPSText : MonoBehaviour {
 
	public Text coordinates;
 
	private void Update()
	{
		coordinates.text = "Lat:" + GPS.Instance.latitude.ToString () + "    Long:" + GPS.Instance.longitude.ToString ();
	}
}