using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.Networking; public class WeatherManager : MonoBehaviour { // 天气 API 地址和密钥 private const string apiKey = "444d87185b76dc18e26b4a60041ff9a7"; private const string cityName = "深圳"; // 可以替换为任何城市 private const string weatherUrl = "http://api.openweathermap.org/data/2.5/weather?q={0}&appid={1}&units=metric"; // 单位为摄氏度 // 显示温度的 UI 元素(如果需要显示在 UI 上) public TextMeshProUGUI temperatureText; // 启动时进行请求 void Start() { StartCoroutine(GetWeatherData()); } // 协程获取天气数据 IEnumerator GetWeatherData() { string url = string.Format(weatherUrl, cityName, apiKey); // 构建请求 URL UnityWebRequest request = UnityWebRequest.Get(url); yield return request.SendWebRequest(); // 等待请求响应 if (request.result == UnityWebRequest.Result.Success) { // 解析返回的 JSON 数据 string jsonResponse = request.downloadHandler.text; WeatherResponse weatherResponse = JsonUtility.FromJson(jsonResponse); // 获取温度信息 float temperature = weatherResponse.main.temp; Debug.Log("当前温度: " + temperature + "°C"); // 如果有 UI 显示温度,可以更新 UI if (temperatureText != null) { temperatureText.text = "当前温度: " + temperature + "°C"; } } else { Debug.LogError("请求失败: " + request.error); } } // 用于解析 JSON 响应的类 [System.Serializable] public class WeatherResponse { public Main main; } [System.Serializable] public class Main { public float temp; // 温度 } }