Unity天气API请求(高德)

1.创建高德账户:首页 | 高德控制台

2.创建Key:我的应用 | 高德控制台

3.获取API:天气查询 - 高德地图 API

var client = new RestClient("https://restapi.amap.com/v3/weather/weatherInfo?Key=");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

4.获取目标城市编码表:相关下载-Web服务 API | 高德地图API

4.改为unity中的请求方式:

  void Start()
    {
        StartCoroutine(RequestForWeather());
    }

[Serializable]
    public class WeatherResponse
    {
        public string status;
        public string count;
        public string info;
        public string infocode;
        public Live[] lives;
    }

    [Serializable]
    public class Live
    {
        public string province;
        public string city;
        public string adcode;
        public string weather;
        public string temperature;
        public string winddirection;
        public string windpower;
        public string humidity;
        public string reporttime;
        public string temperature_float;
        public string humidity_float;
    } 

IEnumerator RequestForWeather()
    {
        string key = "123456";//自己的Key
        string city = "320320"; // 可根据需要赋值
        string extensions = "base"; // 可根据需要赋值
        string output = "JSON"; // 可根据需要赋值
        string url = $"https://restapi.amap.com/v3/weather/weatherInfo?Key={key}&city={city}&extensions={extensions}&output={output}";
        using (UnityEngine.Networking.UnityWebRequest request = UnityEngine.Networking.UnityWebRequest.Get(url))
        {
            yield return request.SendWebRequest();

#if UNITY_2020_1_OR_NEWER
            if (request.result == UnityEngine.Networking.UnityWebRequest.Result.ConnectionError || request.result == UnityEngine.Networking.UnityWebRequest.Result.ProtocolError)
#else
            if (request.isNetworkError || request.isHttpError)
#endif
            {
                Debug.LogError(request.error);
            }
            else
            {
                Debug.Log(request.downloadHandler.text);
                try
                {
                    WeatherResponse weatherResponse = JsonUtility.FromJson<WeatherResponse>(request.downloadHandler.text);
                    if (weatherResponse != null && weatherResponse.lives != null && weatherResponse.lives.Length > 0)
                    {
                        //根据自己的需求解析
                        string date = DateTime.Now.ToString("yyyy-MM-dd");
                        string time = DateTime.Now.ToString("HH:mm");
                        weatherText.text = $"{live.weather}   {date}  {time}";
                    }
                    else
                    {
                        weatherText.text = "未获取到天气信息";
                    }
                }
                catch (Exception ex)
                {
                    weatherText.text = "解析天气信息失败: " + ex.Message;
                }
            }
        }
    }

结果:

### 集成高德天气 APIUnity 的方法 要在 Unity 中调用高德天气 API 并实现天气效果,可以按照以下方式完成: #### 1. 注册并获取高德开放平台密钥 开发者需要先注册成为高德开放平台的用户,并创建应用以获得专属的 API Key。此密钥用于身份验证和访问权限控制[^1]。 #### 2. 调用高德天气接口 高德地图提供了多种类型的天气数据查询服务,例如实时天气、未来几天预报以及历史天气记录等。通过 HTTP 请求发送 GET 或 POST 方法到指定 URL 即可获取所需的数据。以下是常用的请求地址模板: - **实时天气查询**: `https://restapi.amap.com/v3/weather/weatherInfo?key=您的Key&city=城市名&type=live`[^2] 其中参数说明如下: - key: 开发者申请的应用程序唯一标识符; - city: 所需查询的城市名称或者行政区划编码; - type: 数据返回模式,“live”表示当前实况,“forecast”则代表多日预测信息。 #### 3. 使用 C# 编写脚本发起网络请求Unity 环境下利用内置库 UnityEngine.Networking 来构建异步加载过程非常方便快捷。下面展示了一个简单的例子来演示如何从服务器端拉取 JSON 格式的气象资料并解析它。 ```csharp using System.Collections; using UnityEngine; public class WeatherFetcher : MonoBehaviour { public string apiKey; // 设置为你的高德API密钥 public string cityName = "北京"; void Start() { StartCoroutine(GetWeather()); } IEnumerator GetWeather(){ WWWForm form = new WWWForm(); var url = $"https://restapi.amap.com/v3/weather/weatherInfo?city={cityName}&type=live&key={apiKey}"; using (var www = UnityWebRequest.Get(url)) { yield return www.SendWebRequest(); if(www.result != UnityWebRequest.Result.Success){ Debug.LogError($"Error:{www.error}"); } else{ ProcessJsonResponse(www.downloadHandler.text); } } } private void ProcessJsonResponse(string jsonResponse){ // 解析JSON字符串... Debug.Log(jsonResponse); } } ``` 上述代码片段展示了如何向高德天气 API 发起一次同步请求,并处理响应中的原始 JSON 文本[^3]。 #### 4. 动态调整场景环境匹配实际气候状况 一旦成功接收到来自云端的服务反馈之后,就可以依据这些数值改变游戏世界里的光照强度、天空盒材质贴图以及其他视觉特效属性从而营造出身临其境的感觉。比如当检测到阴雨连绵的日子时降低整体亮度等级同时播放淅沥声效;如果是晴朗明媚的好日子就让太阳升起照亮整个区域等等[^4]。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值