using UnityEngine;
using UnityEngine.Networking;
using System.Collections;
public class GeoLocation : MonoBehaviour
{
private const string apiUrl = "https://ipinfo.io/json";
void Start()
{
StartCoroutine(GetGeoLocation());
}
IEnumerator GetGeoLocation()
{
using (UnityWebRequest www = UnityWebRequest.Get(apiUrl))
{
yield return www.SendWebRequest();
if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
{
Debug.Log(www.error);
}
else
{
string jsonResponse = www.downloadHandler.text;
LocationData locationData = JsonUtility.FromJson<LocationData>(jsonResponse);
DetermineRegion(locationData);
}
}
}
void DetermineRegion(LocationData locationData)
{
if (locationData.region != null)
{
if (locationData.region.Contains("Europe"))
{
Debug.Log("用户来自欧洲");
}
else if (locationData.region.Contains("America"))
{
Debug.Log("用户来自美洲");
}
else
{
Debug.Log("用户来自其他地区: " + locationData.region);
}
}
}
}
[System.Serializable]
public class LocationData
{
public string ip;
public string city;
public string region;
public string country;
}
08-17
1658
07-10
02-09
2036