SHOW:
|
|
- or go back to the newest paste.
1 | using UnityEngine; | |
2 | using UnityEngine.Networking; | |
3 | using System.Collections; | |
4 | using SimpleJSON; | |
5 | ||
6 | // Based on snippet written by Unity forum user johnnydj | |
7 | // see https://forum.unity.com/threads/current-weather-script.242009/ | |
8 | ||
9 | public class GetMyWeather : MonoBehaviour | |
10 | { | |
11 | public string currentCountry = "Canada"; | |
12 | public string currentCity = "Toronto"; | |
13 | - | public string appID = "8b22238c3add792f25ca7c26047a9d81"; |
13 | + | public string appID = <OpenWeatherMap.Org APPID here!>; |
14 | ||
15 | //retrieved from weather API | |
16 | private string jsonString; | |
17 | - | public Light sun1; |
17 | + | |
18 | - | public Light sun2; |
18 | + | |
19 | - | public Light sun3; |
19 | + | |
20 | public string conditionName; | |
21 | public float tempCelcius = 0; | |
22 | public float humidity; | |
23 | ||
24 | void Start() | |
25 | { | |
26 | string url = "http://api.openweathermap.org/data/2.5/weather?q=" + currentCity + "&APPID=" + appID; | |
27 | StartCoroutine(GetRequest(url)); | |
28 | } | |
29 | ||
30 | private void FixedUpdate() | |
31 | { | |
32 | // Drawing events here? | |
33 | } | |
34 | ||
35 | IEnumerator GetRequest(string uri) | |
36 | { | |
37 | using (UnityWebRequest request = UnityWebRequest.Get(uri)) | |
38 | { | |
39 | //get the current weather | |
40 | yield return request.SendWebRequest(); | |
41 | ||
42 | string[] pages = uri.Split('/'); | |
43 | int page = pages.Length - 1; | |
44 | ||
45 | if (request.isNetworkError) | |
46 | { | |
47 | Debug.Log(pages[page] + ": Error: " + request.error); | |
48 | } | |
49 | else | |
50 | { | |
51 | jsonString = request.downloadHandler.text; | |
52 | Debug.Log(pages[page] + ":\nReceived: " + jsonString); | |
53 | ||
54 | // https://openweathermap.org/current#current_JSON | |
55 | var N = JSON.Parse(jsonString); // Parseable JSON object | |
56 | ||
57 | retrievedCountry = N["sys"]["country"].Value; //get the country | |
58 | retrievedCity = N["name"].Value; //get the city | |
59 | ||
60 | string temp = N["main"]["temp"].Value; //get the temperature | |
61 | float tempFloat; //variable to hold the parsed temperature | |
62 | float.TryParse(temp, out tempFloat); //parse the temperature | |
63 | tempCelcius = Mathf.Round((tempFloat - 273.0f) * 10) / 10; //holds the actual converted temperature | |
64 | ||
65 | temp = N["main"]["humidity"].Value; | |
66 | float.TryParse(temp, out humidity); // Captures humidity (%) | |
67 | ||
68 | // https://openweathermap.org/weather-conditions | |
69 | int.TryParse(N["weather"][0]["id"].Value, out conditionID); //get the current condition ID | |
70 | //conditionName = N["weather"][0]["main"].Value; //get the current condition Name | |
71 | conditionName = N["weather"][0]["description"].Value; //get the current condition Description | |
72 | } | |
73 | ||
74 | } | |
75 | } | |
76 | } |