I am building a location based game, a bit like pokemon go.
I am reading the location on my android phone without any problem, but I can't get any location data when I'm developing in the unity editor since Input.location.isEnabledByUser is false in the editor
It would be ok to mock/hard code a location, just so I can try it without deploying to my phone.
I tried to hard code it like this:
LocationInfo ReadLocation(){
#if UNITY_EDITOR
var location = new LocationInfo();
location.latitude = 59.000f;
location.longitude = 18.000f;
location.altitude= 0.0f;
location.horizontalAccuracy = 5.0f;
location.verticalAccuracy = 5.0f;
return location;
#elif
return Input.location.lastData;
#endif
}
But all of the properties of the location are read only, so I'm getting compilation errors.
Is there a way to enable location service in the editor, or hardcode a location?
Best Answer
This is one of the reasons why Unity Remote was made. Setup Unity Remote then connect your mobile device to the Editor. You can now get a real location from the Editor.
If you really want to develop a way to mock the location, you have to abandon Unity's
LocationInfo
structure. Make your own customLocationInfo
and name itLocationInfoExt
. Ext is = Extended.Do the-same thing for
LocationService
too, then Wrap the officialLocationService
into your customLocationServiceExt
class. You can useLocationServiceExt
to decide if you should mock location by usingLocationInfoExt
or not mock location by usingLocationInfo
internally to provide the result.In the example below, the official
LocationService
,LocationInfo
andLocationServiceStatus
class/struct/enum are replaced withLocationServiceExt
,LocationInfoExt
andLocationServiceStatusExt
. They also have the-same functions and properties implemented. The only difference is that you can pass true/false to the constructor ofLocationServiceExt
in order to use it in the Editor.LocationServiceExt
wrapper class:Create a class called
LocationServiceExt
then copy the code below into it: It has every function and property from the originalLocationService
class.Usage:
Create a mock location
Create a real location
Modify the location later on
Full ported working example from Unity Doc.