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


}

三、最终效果

相关推荐
mxwin4 小时前
Unity URP 下抓取当前屏幕内容实现扭曲、镜子与全局模糊效果
unity·游戏引擎·shader
南無忘码至尊9 小时前
Unity学习90天-第2天-认识Unity生命周期函数并用 Update 控制物体移动,FixedUpdate 控制物理
学习·unity·游戏引擎
小林up13 小时前
【Unity URP源码阅读1】ColorGradingLUT
unity·游戏引擎
风酥糖16 小时前
Godot游戏练习01-第27节-升级选项选择生效
游戏·游戏引擎·godot
郝学胜-神的一滴16 小时前
[简化版 GAMES 101] 计算机图形学 04:二维变换上
c++·算法·unity·godot·图形渲染·unreal engine·cesium
南無忘码至尊17 小时前
Unity学习90天-第2天-认识键盘 / 鼠标输入(PC)并实现WASD 移动,鼠标控制物体转向
学习·unity·c#·游戏开发
星夜泊客17 小时前
unity 海底海洋资源OceanEnviromentPackUrp材质丢失修正
unity·游戏引擎·材质
weixin_4242946718 小时前
Unity 的Button Animator
unity·游戏引擎
UQ_rookie19 小时前
【Unity3D】在URP渲染管线下使用liltoon插件出现粉色无法渲染情况的解决方案
unity·游戏引擎·shader·urp·着色器·vrchat·liltoon
aqiu~1 天前
VSCode编辑器用于Unity项目
vscode·unity