Unity通过高德开放平台获取天气信息
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);
}
}
}
}