GeoLocation.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. using UnityEngine;
  2. using UnityEngine.Networking;
  3. using System.Collections;
  4. /* 获取用户ip地址,国家,地区,城市信息
  5. */
  6. public class GeoLocation : MonoBehaviour
  7. {
  8. private const string apiUrl = "https://ipinfo.io/json";
  9. void Start()
  10. {
  11. StartCoroutine(GetGeoLocation());
  12. }
  13. IEnumerator GetGeoLocation()
  14. {
  15. using (UnityWebRequest www = UnityWebRequest.Get(apiUrl))
  16. {
  17. yield return www.SendWebRequest();
  18. if (www.result == UnityWebRequest.Result.ConnectionError || www.result == UnityWebRequest.Result.ProtocolError)
  19. {
  20. Debug.Log(www.error);
  21. }
  22. else
  23. {
  24. string jsonResponse = www.downloadHandler.text;
  25. LocationData locationData = JsonUtility.FromJson<LocationData>(jsonResponse);
  26. DetermineRegion(locationData);
  27. }
  28. }
  29. }
  30. void DetermineRegion(LocationData locationData)
  31. {
  32. if (locationData.region != null)
  33. {
  34. if (locationData.region.Contains("Europe"))
  35. {
  36. Debug.Log("用户来自欧洲");
  37. }
  38. else if (locationData.region.Contains("America"))
  39. {
  40. Debug.Log("用户来自美洲");
  41. }
  42. else
  43. {
  44. Debug.Log("用户来自其他地区: " + locationData.region);
  45. }
  46. }
  47. }
  48. }
  49. [System.Serializable]
  50. public class LocationData
  51. {
  52. public string ip;
  53. public string city;
  54. public string region;
  55. public string country;
  56. }