Current Weather Script

Was bored today at work and I made a Script that retrieves current weather conditions based on the player’s IP address.
It is using SimpleJSON so make sure you DOWNLOAD HERE then import the unitypackage into your project.
Then just copy paste the below code into a C# script.

It is using NGUI label and texture so if you don’t have it, just replace
public UILabel myWeatherLabel;
public UITexture myWeatherCondition;
with the GUI versions.

using UnityEngine;
using System.Collections;
using SimpleJSON;

public class GetMyWeather : MonoBehaviour {

    public UILabel myWeatherLabel;
    public UITexture myWeatherCondition;

    public string currentIP;
    public string currentCountry;
    public string currentCity;

    //retrieved from weather API
    public string retrievedCountry;
    public string retrievedCity;
    public int conditionID;
    public string conditionName;
    public string conditionImage;

    void Start()
    {
        StartCoroutine(SendRequest());
    }

    IEnumerator SendRequest()
    {
        //get the players IP, City, Country
        Network.Connect("http://google.com");
        currentIP = Network.player.externalIP;
        Network.Disconnect();

        WWW cityRequest = new WWW("http://www.geoplugin.net/json.gp?ip=" + currentIP); //get our location info
        yield return cityRequest;

        if (cityRequest.error == null || cityRequest.error == "")
        {
            var N = JSON.Parse(cityRequest.text);
            currentCity = N["geoplugin_city"].Value;
            currentCountry = N["geoplugin_countryName"].Value;
        }

        else
        {
            Debug.Log("WWW error: " + cityRequest.error);
        }

        //get the current weather
        WWW request = new WWW("http://api.openweathermap.org/data/2.5/weather?q=" + currentCity); //get our weather
        yield return request;

        if (request.error == null || request.error == "")
        {
            var N = JSON.Parse(request.text);

            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 tempTemp; //variable to hold the parsed temperature
            float.TryParse(temp, out tempTemp); //parse the temperature
            float finalTemp = Mathf.Round((tempTemp - 273.0f)*10)/10; //holds the actual converted temperature

            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
            conditionImage = N["weather"][0]["icon"].Value; //get the current condition Image

            //put all the retrieved stuff in the label
            myWeatherLabel.text = 
                "Country: " + retrievedCountry
                + "\nCity: " + retrievedCity
                + "\nTemperature: " + finalTemp + " C"
                + "\nCurrent Condition: " + conditionName 
                + "\nCondition Code: " + conditionID;
        }
        else
        {
            Debug.Log("WWW error: " + request.error);
        }

        //get our weather image
        WWW conditionRequest = new WWW("http://openweathermap.org/img/w/" + conditionImage + ".png"); 
        yield return conditionRequest;

        if (conditionRequest.error == null || conditionRequest.error == "")
        {
            //create the material, put in the downloaded texture and make it visible
            var texture = conditionRequest.texture;
            Shader shader = Shader.Find("Unlit/Transparent Colored");
            if (shader != null)
            {
                var material = new Material(shader);
                material.mainTexture = texture;
                myWeatherCondition.material = material;
                myWeatherCondition.color = Color.white;
                myWeatherCondition.MakePixelPerfect();
            }
        }
        else
        {
            Debug.Log("WWW error: " + conditionRequest.error);
        }
    }
}
5 Likes

This has great potential, for a game in which you make the game environment reflect the weather outside.
Do you attack your enemys now, or build up and attack on a foggy day!
Cue players looking at the weather forecast to plan their strategy.

1 Like

hello,
this script is awesome…
but i want to use this in my game and for that i want name of all weather conditions…so i can imply weather in game according to that…
can you help
thank you

Compliments mate (y)
Saved a lot of time.

Awesome! I have always wondered what it would be like to have a game where the weather outside affected the game world. This looks to be what I need to try to make that myself since I never got around to trying to figure it out for myself. Thanks for sharing!

Edit: And for those who are looking for a list of conditions so you can do neat things in game like I want to, I think this is what we need(as I see it’s polling openweathermap.org for the data in the script):
Weather Conditions - OpenWeatherMap

This is really cool.

Thanks for sharing!

Assets/SimpleJSON/JSON Tests/UnityScript/Test_UnityScript.js(3,8): BCE0021: Namespace ‘SimpleJSON’ not found, maybe you forgot to add an assembly reference?

Could it be because the website changed and now you need an account?

And also, it seems to be deprecated :frowning:

Cant find the equal class method for Network.Connect, unity says to use Multiplayer or Network identity but no help by going through them. WWW as deprecated but UnityWebReq has good documentation. any help on Network.Connect ?

No Way!! Good job! I would make your own weather system integration with it if I were you!

Could you send me all diffrend variation you can get out of it?
like a list of weather: rainy, foggy just like that, and all of the aviable countrys and citys?

Doesn’t seem to work for Unity 2021.1. I keep getting a ton of errors

How would you get the image part working? I cannot get that to work. The shader part isn’t working. Did anyone figure that part out?