Unity通过高德开放平台获取天气信息

一、注册高德开放平台账号,获取天气接口Key

1、构建自己的应用

网址:https://lbs.amap.com/api/webservice/guide/api/weatherinfo

最终调用api的地址形式:

https://restapi.amap.com/v3/weather/weatherInfo?city=110101\&key=\<用户key>

二、Unity中写算法进行调用

具体代码:

csharp 复制代码
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class GetWeather : MonoBehaviour
{
    public string url;
    public Button getweather;
    public Text weatherInfo;


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

    // Start is called before the first frame update
    void Start()
    {
        getweather.onClick.AddListener(GetWeatherInfo);
    }

    void GetWeatherInfo()
    {
        LoadNetJson<LivesData>(url,
        (data) =>
        {
            weatherInfo.text = data.lives[0].province;
            weatherInfo.text += data.lives[0].weather;
            weatherInfo.text += data.lives[0].temperature + "°C";
            weatherInfo.text += data.lives[0].winddirection + "风";
        },
        (error) =>
        {
            Debug.Log(error);
        }
        );
    }

    //读取网络Json
    public void LoadNetJson<T>(string url, Action<T> onSuccess, Action<string> onError)
    {
        StartCoroutine(FetchDate(url, onSuccess, onError));
    }
    //等待网络返回携程
    private IEnumerator FetchDate<T>(string url, Action<T> onSuccess, Action<string> onError)
    {
        using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
        {
            yield return webRequest.SendWebRequest();

            if (webRequest.result != UnityWebRequest.Result.Success)
            {
                onError?.Invoke(webRequest.error);
            }
            else
            {
                string json = webRequest.downloadHandler.text;
                T data = JsonUtility.FromJson<T>(json);
                onSuccess?.Invoke(data);
            }
        }
    }


}

三、最终效果

相关推荐
gshh__10 小时前
SuperMap Hi-Fi 3D SDK for Unreal 如何修改模型选中高亮颜色
ue5·游戏引擎·supermap
沉默金鱼20 小时前
Unity实用技能-GM命令
unity·游戏引擎
chillxiaohan21 小时前
unity粗糙、高光、光泽度调节shader记录
unity·游戏引擎
星夜泊客1 天前
Unity UI 渲染与 Rebuild 机制简易解析
unity·游戏引擎
一线灵1 天前
跨平台游戏引擎 Axmol-2.11.1 发布
游戏引擎
qiminixi1 天前
Unity 6000下载
unity·unity 6000·unity 6000下载
CreasyChan2 天前
Unity Shader 入门指南
unity·c#·游戏引擎·shader
漂视数字孪生世界2 天前
Unity团结引擎的前世今生
unity·游戏引擎·数字孪生
心前阳光2 天前
Unity通过ScriptableObject学习访问者模式
学习·unity·访问者模式
fcm192 天前
unity之重新导入TMP
unity