[Unity] OpenAPI를 이용하여 실제 날씨 불러오기

JH Park·2021년 7월 8일
0

Unity

목록 보기
3/3

1. OpenWeather API 회원가입

https://www.youtube.com/watch?v=G92bOA2WiO4
이 사이트에서 지역에 따른 날씨를 불러올 수 있다.
간단한 회원가입하면 각자 api key를 받는데 이를 코드에 이용해야 한다.

2. Code

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;

}

Weather API의 형태

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class Weather : MonoBehaviour
{
    public string APP_ID;
    public Text weatherText;
    public WeatherData weatherInfo;

    // Start is called before the first frame update
    void Start()
    {
        CheckCityWeather("Seoul");
    }

    public void CheckCityWeather(string city)
    {
        StartCoroutine(GetWeather(city));
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    IEnumerator GetWeather(string city)
    {
        city = UnityWebRequest.EscapeURL(city);
        string url = "http://api.openweathermap.org/data/2.5/weather?q=Seoul&units=metric&appid=본인 api key";

        UnityWebRequest www = UnityWebRequest.Get(url);
        yield return www.SendWebRequest();

        string json = www.downloadHandler.text;
        json = json.Replace("\"base\":", "\"basem\":");
        weatherInfo = JsonUtility.FromJson<WeatherData>(json);
        
        if(weatherInfo.weather.Length>0)
        {
            weatherText.text=weatherInfo.weather[0].main;
        }
        
    }
}

OpenWeather에서 날씨를 불러오는 코드다.
API가 json 형태라 변환해줬다.

*json이란?

일반적으로 서버에서 클라이언트로 데이터를 보낼 때 사용하는 형식

3. 결과

Debug를 찍으니 날씨가 Clear라고 잘 뜬다.

어려울까봐 걱정했는데 유튜브 영상보면서 천천히 따라하니 이해도 잘되고 큰 어려움 없었다.
게임에 현재 날씨를 불러와서 꾸미니 훨씬 다채로워졌다!!

참고한 영상: https://www.youtube.com/watch?v=G92bOA2WiO4

profile
Computer Engineering Student

0개의 댓글