So you want to access the user’s device location. Maybe you are working on a location-based game like Pokemon GO or maybe you are matching players to others in their vicinity. There are multiple ways to get a player’s location. Read my other post to learn about 3 ways to decide user’s location. In any case, let’s jump in!
Unity has a
LocationServiceclass that deals with the GPS location. It can be accessed via
Input.location . The documentation on Unity website is minimal (not surprisingly). There is a sample code on this page, which is all over internet for how to use location in Unity. So as I started using the class I faced multiple issues. Here I’m going to explain what went wrong and how to fix them!
I’ve shared my final code at the end of this post. You can skip the rest of this post, copy the code to your projects and use it. But it’s probably a good idea to finish reading so that you know what’s going on.
Let’s walk through the base code from the Unity sample. The code:
- checks if the location service is enabled on the device. This is a Unity internal check which is vague. As far as I can tell, on Android it checks whether we have permission, where as on iOS is checks whether the operating system’s location service is on.
- Start the service.
- Wait for location to become available.
- Read location or timeout depending on the status of the service.
The sample code from Unity’s website doesn’t work with Unity Remote. A big hindrance for development. Let’s go ahead and fix that!
It takes a while for Unity connect to start reporting location and until then, the location lookups fail. To get around that we:
- Wait for Unity Remote to connect (lines 8–12)
- Wait extra since the service status doesn’t turn to Initializing with Unity Remote as result of a bug in Unity (lines 43–50)
You need to ask for permission from the user before you can read location from the LocationService class. To do that, we use the
UnityEngine.Android.Permission class (Lines 14–18).
On iOS, we need location access. To do that, we need to provide the settings field for it under
Project Settings -> Player -> iOS -> Location Usage Description . Any non-empty value will do. This is particularly important since without it everything seems to work but the location lookups fail silently.
We could also ignore the value of
UnityEngine.Input.location.isEnabledByUser to run the service on iOS. (comment out lines 26–32)
Combining everything from above, the code for our location class looks like this. Feel free to start with this as your base and build upon it for your specific project. Also checkout my follow up post on how to perform offline reverse geocode queries to get users’ country and US state.
As a software engineer turned indie game developer, I write about the technical problems I encounter. Follow me here or on instagram (IG:@no_such_studio ) to learn more about game development, Unity and programming.