Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- using UnityEngine.Networking;
- using System.Collections;
- using SimpleJSON;
- // Based on snippet written by Unity forum user johnnydj
- // see https://forum.unity.com/threads/current-weather-script.242009/
- public class GetMyWeather : MonoBehaviour
- {
- public string currentCountry = "Canada";
- public string currentCity = "Toronto";
- public string appID = <OpenWeatherMap.Org APPID here!>;
- //retrieved from weather API
- private string jsonString;
- public string retrievedCountry;
- public string retrievedCity;
- public int conditionID;
- public string conditionName;
- public float tempCelcius = 0;
- public float humidity;
- void Start()
- {
- string url = "http://api.openweathermap.org/data/2.5/weather?q=" + currentCity + "&APPID=" + appID;
- StartCoroutine(GetRequest(url));
- }
- private void FixedUpdate()
- {
- // Drawing events here?
- }
- IEnumerator GetRequest(string uri)
- {
- using (UnityWebRequest request = UnityWebRequest.Get(uri))
- {
- //get the current weather
- yield return request.SendWebRequest();
- string[] pages = uri.Split('/');
- int page = pages.Length - 1;
- if (request.isNetworkError)
- {
- Debug.Log(pages[page] + ": Error: " + request.error);
- }
- else
- {
- jsonString = request.downloadHandler.text;
- Debug.Log(pages[page] + ":\nReceived: " + jsonString);
- // https://openweathermap.org/current#current_JSON
- var N = JSON.Parse(jsonString); // Parseable JSON object
- retrievedCountry = N["sys"]["country"].Value; //get the country
- retrievedCity = N["name"].Value; //get the city
- string temp = N["main"]["temp"].Value; //get the temperature
- float tempFloat; //variable to hold the parsed temperature
- float.TryParse(temp, out tempFloat); //parse the temperature
- tempCelcius = Mathf.Round((tempFloat - 273.0f) * 10) / 10; //holds the actual converted temperature
- temp = N["main"]["humidity"].Value;
- float.TryParse(temp, out humidity); // Captures humidity (%)
- // https://openweathermap.org/weather-conditions
- int.TryParse(N["weather"][0]["id"].Value, out conditionID); //get the current condition ID
- //conditionName = N["weather"][0]["main"].Value; //get the current condition Name
- conditionName = N["weather"][0]["description"].Value; //get the current condition Description
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement