Unity获取当前城市天气

完善了根据当前IP查询所在城市编码,然后根据城市编码获取当前城市天气,DEMO下载地址
参考http://blog.csdn.net/wjb0108/article/details/41380193
效果:   
代码如下:
using UnityEngine;  
using System.Collections;  
using System.IO;  
using LitJson;
using System.Text.RegularExpressions;
using System.Xml;
using System.Text;
public class WeatherTest : MonoBehaviour
{
   
    private string m_url = "http://www.weather.com.cn/data/cityinfo/";//上海天气  101210101.html
    public string lbCity;//城市  
    public string lbTemperature;//温度  
    public string lbWeahter;//天气  
    public string lbTime;
    public string lbHour;
    public string lbMinute;
    public string lbColon;
    private System.DateTime dNow;
    private string[] dow = { "星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六" };
    private float deltaTime = 0.0f; //update Date  
    private float deltaTimeforWeather = 0.0f; // update Weather  
    private float howlongToUpdate = 3600f;
    void Start()
    {
        StartCoroutine(GetExternalIp());
    }
    void Update()
    {
        //Date  
        dNow = System.DateTime.Now;
        lbTime = dNow.ToString("yyyy年MM月dd日 HH:mm:ss  ") + dow[System.Convert.ToInt16(dNow.DayOfWeek)];
        lbHour = dNow.ToString("HH");
        lbMinute = dNow.ToString("mm");
        deltaTime += Time.deltaTime;
        if (deltaTime > 1.0f)
        {
            deltaTime = 0.0f;
        }
        deltaTimeforWeather += Time.deltaTime;
        if (deltaTimeforWeather > howlongToUpdate)//每一小时更新一次  
        {
            UpdateWeather();
            deltaTimeforWeather = 0.0f;
        }
    }

    public void UpdateWeather()
    {
        StartCoroutine(GetWeather(CityCodeId));
    }
    //void OnEnable()
    //{

    //    UpdateWeather();
    //}
    IEnumerator GetWeather(string CityId)//根据城市ID获取天气信息
    {
        if (m_url != null)
        {
            WWW www = new WWW(m_url + CityId + @".html");
            Debug.Log("URL:"+m_url + CityId + @".html");
            while (!www.isDone) { yield return www; }
            if (www.text != null)
            {
                JsonData jd = JsonMapper.ToObject(www.text);
                JsonData jdInfo = jd["weatherinfo"];
                lbCity = jdInfo["city"].ToString();
                lbTemperature = jdInfo["temp1"].ToString() + "~" + jdInfo["temp2"].ToString();
                lbWeahter = jdInfo["weather"].ToString();
                //。。。。需要的其它信息自己看接口提取
                string strImg1 = jdInfo["img1"].ToString();
                Debug.Log("city:" + lbCity + "\n weather:" + lbWeahter);
            }
        }
    }
    string ip;
    IEnumerator GetExternalIp()//获取当前外网地址
    {
        WWW www = new WWW("http://www.ip138.com/ips138.asp");
        while (!www.isDone) { yield return www; }
        if (www.text != null)
        {           
            Regex r = new Regex("((25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)\\.){3}(25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|[1-9])", RegexOptions.None);
            Match mc = r.Match(www.text);
            ip = mc.Groups[0].Value;
            MacIp = ip;
            StartCoroutine(GetAdrByIp());
        }
    }
    string MacIp;
    IEnumerator GetAdrByIp()//根据IP获取当前城市地址
    {
        //string url = "http://www.ip138.com/ips138.asp?ip=" + MacIp;
        string url = "http://www.ip.cn/index.php?ip=" + MacIp;
        string regStr = "(?<=<div\\s*id=\\\"result\\\">).*?(?=</div>)";
        WWW html = new WWW(url.Trim());
        print("IP查询地址:"+url);
        while (!html.isDone) { yield return html; }        
        if (html.text != null)
        {
            Regex reg = new Regex(regStr, RegexOptions.None);
            Match ma = reg.Match(html.text);            
            City = ma.Value;            
            string resstr;
            resstr = (ReplaceHtmlTag(City).Trim().Split(':')[2].Substring(0, 6)).ToString();
            print(resstr);
            string[] arr = resstr.Split('省');
            Province = arr[0];
            City = arr[1].Replace("市", null); Debug.Log("内容:" + City);
            Xmlfilepath = Application.dataPath + @"/CityWeather/CityCode.xml";
            CityCodeId = ReadXml(Xmlfilepath, City, Province);
            Debug.Log(Province + "省" + City + CityCodeId);
            UpdateWeather();
        }
    }
    string Xmlfilepath;
    string City;
    string Province;
    string CityCodeId;
    public string ReadXml(string filepath, string value, string province)
    {
        string strvalue = null;

        if (File.Exists(filepath))
        {
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(filepath);
            XmlNodeList nodeList = xmlDoc.SelectSingleNode("China").ChildNodes;
            foreach (XmlElement xe in nodeList)
            {
                if (xe.GetAttribute("name") == province)
                {
                    foreach (XmlElement x1 in xe.ChildNodes)
                    {
                        foreach (XmlElement x2 in x1.ChildNodes)
                        {
                            if (x2.GetAttribute("name") == value)
                            {
                                strvalue = x2.GetAttribute("weatherCode");
                            }
                        }
                    }
                }
            }
        } 
        return strvalue;
    }
    public static string ReplaceHtmlTag(string html, int length = 0)//移除HTML标签
    {
        string strText = System.Text.RegularExpressions.Regex.Replace(html, "<[^>]+>", "");
        strText = System.Text.RegularExpressions.Regex.Replace(strText, "&[^;]+;", "");

        if (length > 0 && strText.Length > length)
            return strText.Substring(0, length);

        return strText;
    }  
    void OnGUI()
    {
        GUI.Label(new Rect(60, 40, 200, 25),  "公 网 IP :" + ip);
        GUI.Label(new Rect(60, 70, 200, 25),  "所在城市 :" + Province + "省" + City + "市");
        GUI.Label(new Rect(60, 130, 200, 25), "城市编码:" + CityCodeId);
        GUI.Label(new Rect(60, 160, 200, 25), "城市天气:" + lbWeahter);
        GUI.Label(new Rect(60, 190, 200, 25), "城市气温:" + lbTemperature);
        GUI.Label(new Rect(60, 100, 300, 25), "城市时间:" + lbTime);    
    }
}    


 


                
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
要在Unity3D中获取当前时间,可以使用C#的DateTime类。首先,您需要在脚本中导入System命名空间。然后,您可以使用DateTime.Now属性来获取当前日期和时间。下面是一个示例代码片段: using System; public class TimeManager : MonoBehaviour { private void Start() { string currentTime = GetCurrentTime(); Debug.Log("当前时间:" + currentTime); } private string GetCurrentTime() { DateTime dateTime = DateTime.Now; string strNowTime = string.Format("{0:D}{1:D}{2:D}{3:D}{4:D}{5:D}", dateTime.Year, dateTime.Month, dateTime.Day, dateTime.Hour, dateTime.Minute, dateTime.Second); return strNowTime; } } 在上述代码中,GetCurrentTime()方法返回一个格式化的字符串,包含年、月、日、小时、分钟和秒。您可以根据您的需求修改格式化字符串。然后,您可以在Start()方法中调用GetCurrentTime()方法***<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [Unity3D获取系统当前时间](https://blog.csdn.net/qq_40544338/article/details/114806180)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Unity3D获取当前系统时间并在UI界面中显示](https://blog.csdn.net/weixin_46992165/article/details/126358648)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值