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


}

三、最终效果

相关推荐
玖玥拾2 小时前
Unity Shader 基础与图形学(一)
unity·图形渲染·图形学·shader
WiChP10 小时前
【V0.1B16】从零开始的2D游戏引擎开发之路
开发语言·算法·游戏引擎
百里香酚兰11 小时前
【Unity学习笔记】如何把粉色Prefab还原
笔记·学习·unity
xcLeigh13 小时前
Unity基础:使用Transform控制物体旋转——Rotate与LookAt详解
unity·教程·transform·rotate·lookat
平行云16 小时前
3D应用推流太贵太慢?ImmerShare Lite:利用本地算力实现极简一键分享
unity·ue5·实时云渲染·云桌面·像素流·云游戏·串流
淡海水16 小时前
11-04-Unity-Span-foreach-LINQ的分配与热路径边界
unity·c#·linq·foreach·span
狂人开飞机1 天前
23、实战平台跳跃游戏
游戏·游戏引擎·godot
灸木1 天前
Unity 多线程与并发:什么时候该用多线程?
unity
淡海水2 天前
11-02-Unity-Mono-vs-IL2CPP-两种脚本后端的数据结构行为差异
数据结构·unity·游戏引擎·il2cpp·mono
彧azz2 天前
初学Unity:编辑器
笔记·学习·unity·游戏引擎