using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[System.Serializable]
public class OWM_Coord
{
public float lon;
public float lat;
}
[System.Serializable]
public class OWM_Weather
{
public int id;
public string main;
public string description;
public string icon;
}
[System.Serializable]
public class OWM_Main
{
public int temp;
public float feels_like;
public int temp_min;
public int temp_max;
public int pressure;
public int humidity;
}
[System.Serializable]
public class OWM_Wind
{
public float speed;
public int deg;
}
[System.Serializable]
public class OWM_Clouds
{
public int all;
}
[System.Serializable]
public class OWM_Sys
{
public int type;
public int id;
public string country;
public int sunrise;
public int sunset;
}
[System.Serializable]
public class WeatherData
{
public OWM_Coord coord;
public OWM_Weather[] weather;
public string basem;
public OWM_Main main;
public int visibility;
public OWM_Wind wind;
public OWM_Clouds clouds;
public int dt;
public OWM_Sys sys;
public int timezone;
public int id;
public string name;
public int cod;
}
실시간 스크립트
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
public class Weather : MonoBehaviour
{
//자신의 API키 입력
public string APP_ID;
//날씨 정보 출력할 Text
public Text weatherText;
//아이콘 출력할 RawImage
public RawImage weatherIcon;
public WeatherData weatherInfo;
[Header("도시 이름 입력")]
public string weatherName;
// Start is called before the first frame update
void Start()
{
CheckCityWeather(weatherName);
}
public void CheckCityWeather(string city)
{
StartCoroutine(GetWeather(city));
}
IEnumerator GetWeather(string city)
{
city = UnityWebRequest.EscapeURL(city);
string url = "http://api.openweathermap.org/data/2.5/weather?q="+city+"&units=metric&appid="+APP_ID;
UnityWebRequest www = UnityWebRequest.Get(url);
yield return www.SendWebRequest();
string json = www.downloadHandler.text;
json = json.Replace("\"base\":", "\"basem\":");
weatherInfo = JsonUtility.FromJson<WeatherData>(json);
//입력한 도시 이름 + 몇 도인지 소수점 올림
weatherText.text = weatherInfo.name + "\n";
weatherText.text += weatherInfo.main.temp.ToString("N1") + " °C \n";
if (weatherInfo.weather.Length > 0)
{
//weatherText.text = weatherInfo.weather[0].main;
weatherText.text += weatherInfo.weather[0].description;
StartCoroutine(GetWeatherIcon(weatherInfo.weather[0].icon));
}
}
//아이콘 텍스쳐를 다운 받아서 출력
IEnumerator GetWeatherIcon(string icon)
{
string url = "http://openweathermap.org/img/wn/" + icon + "@2x.png";
UnityWebRequest www = UnityWebRequestTexture.GetTexture(url);
yield return www.SendWebRequest();
weatherIcon.gameObject.SetActive(true);
weatherIcon.texture = DownloadHandlerTexture.GetContent(www);
}
}