简体   繁体   English

unity C# 如何获取玩家的国家、城市或位置

[英]Unity C# How to get country, city or location of a player

I've a game where I'm trying to keep my own analytics.我有一个游戏,我试图保留自己的分析。 No pin point location, is there something similar to SystemInfo class that could give approximate location of the player?没有精确定位,是否有类似于SystemInfo class 的东西可以给出播放器的大致位置?

I know I can tap into the GPS but I don't want to make things complicated.我知道我可以利用 GPS,但我不想让事情变得复杂。 Just a simple city or country will do.一个简单的城市或国家就可以了。

Please advise.请指教。

You can either ask the user for their details or send a request to your web server where that uses something like ipdata.co to track where the IP address came from.您可以向用户询问他们的详细信息,也可以向您的 web 服务器发送请求,该服务器使用ipdata.co之类的东西来跟踪 IP 地址的来源。

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如果您想将其更改为城市或其他任何内容,您只需按照以下链接向IpApiData添加一些字段: https://ipapi.co/api/#complete-location

You can first take the IP of the player.可以先拿播放器的IP。 I think this might helpanswers.unity.com/questions/518346/get-ipv4-adress .我认为这可能有助于answers.unity.com/questions/518346/get-ipv4-adress Then use any site IP-tracker to find the location.然后使用任何站点 IP 跟踪器来查找位置。 (like ipstack ) (如ipstack

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM