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);
            }
        }
    }


}

三、最终效果

相关推荐
90后小陈老师7 小时前
Unity教学 项目2 2D闯关游戏
游戏·unity·游戏引擎
噗噗夹的TA之旅7 小时前
Unity Shader 学习20:URP LitForwardPass PBR 解析
学习·unity·游戏引擎·图形渲染·技术美术
nnsix8 小时前
Unity ReferenceFinder插件 多选资源查找bug解决
unity·游戏引擎·bug
gzroy9 小时前
Unity Shader Graph实现全息瞄准器
unity·游戏引擎
90后小陈老师12 小时前
Unity教学 基础介绍
unity·游戏引擎
90后小陈老师12 小时前
Unity教学 项目3 3D坦克大战
3d·unity·游戏引擎
秦奈14 小时前
Unity复习学习随笔(五):Unity基础
学习·unity·游戏引擎
nnsix15 小时前
Unity ReferenceFinder插件 窗口中选择资源时 同步选择Assets下的资源
java·unity·游戏引擎
麷飞花16 小时前
unity3d scene窗口选中物体, 在 hierarchy高光显示
unity·editor·unity3d·u3d·hierarchy
ۓ明哲ڪ17 小时前
Unity功能——关闭脚本自动编译(Unity2021.3)
unity·游戏引擎