I had this problem too, so I wanted to make as simple of a solution as possible. Unfortunately, it wasn't easy:
[Serializable]
public class IpApiData
{
public string country_name;
public static IpApiData CreateFromJSON(string jsonString)
{
return JsonUtility.FromJson<IpApiData>(jsonString);
}
}
public static IEnumerator SetCountry()
{
string ip = new System.Net.WebClient().DownloadString("https://api.ipify.org");
string uri = $"https://ipapi.co/{ip}/json/";
using (UnityWebRequest webRequest = UnityWebRequest.Get(uri))
{
yield return webRequest.SendWebRequest();
string[] pages = uri.Split('/');
int page = pages.Length - 1;
IpApiData ipApiData = IpApiData.CreateFromJSON(webRequest.downloadHandler.text);
Debug.Log(ipApiData.country_name);
}
}
This will get the country, no problem. If you want to change it to city, or anything else, you'll just have to add some fields to IpApiData
, as per this link: https://ipapi.co/api/#complete-location