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


}

三、最终效果

相关推荐
Yasin Chen5 小时前
C# Dictionary源码分析
算法·unity·哈希算法
深海潜水员13 小时前
【Behavior Tree】-- 行为树AI逻辑实现- Unity 游戏引擎实现
游戏·unity·c#
Thomas_YXQ1 天前
Unity3D游戏内存优化指南
游戏·unity·职场和发展·性能优化·蓝桥杯·游戏引擎·unity3d
chillxiaohan1 天前
Unity接入Steamworks.NET实现通信功能
unity
枯萎穿心攻击1 天前
响应式编程入门教程第二节:构建 ObservableProperty<T> — 封装 ReactiveProperty 的高级用法
开发语言·unity·c#·游戏引擎
X_StarX2 天前
【Unity笔记02】订阅事件-自动开门
笔记·学习·unity·游戏引擎·游戏开发·大学生
霸王•吕布2 天前
游戏引擎中顶点着色&像素着色
游戏引擎·顶点着色器·像素着色器·顶点颜色·顶点uv·顶点法向
一线灵2 天前
跨平台游戏引擎 Axmol-2.7.0 发布
c++·游戏引擎·wasm·axmol·cocos2dx
Thomas_YXQ2 天前
Unity URP法线贴图实现教程
开发语言·unity·性能优化·游戏引擎·unity3d·贴图·单一职责原则
徐子竣2 天前
[学习记录]Unity-Shader-几何着色器
unity·游戏引擎·着色器