1. 程式人生 > >http協議下載資源及訪問url(登入註冊);

http協議下載資源及訪問url(登入註冊);

using UnityEngine;
using System.Collections;
/// <summary>
/// using UnityEngine;
using System.Collections;
/// <summary>
/// http協議下載資源及訪問url(登入註冊);
/// </summary>
public class HttpDownLoad : MonoBehaviour {

    /// <summary>
    ///委託   下載之後的回撥
    /// </summary>
    /// <param name="bytes"></param>
    public delegate void AccessURLCallBack(string url ,byte[] bytes);
    /// <summary>
    /// 單例物件
    /// </summary>
    private static HttpDownLoad _instance;

    public static HttpDownLoad GetInstance()
    {
        if (_instance==null)
        {
            //想辦法建立
            GameObject gb = new GameObject();
            //建立具體的單例
           _instance= gb.AddComponent<HttpDownLoad>();
        }
        return _instance;
    }

    void Start() {
        _instance = this;
    }

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

    }
    /// <summary>
    /// 啟動協程
    /// </summary>
    public void StartCoroutineAccessURL(string url,AccessURLCallBack callBack)
    {
        StartCoroutine(AccessURL(url,callBack));
    }
    /// <summary>
    /// 訪問URL協程
    /// </summary>
    /// <param name="URL"></param>
    /// <returns></returns>
    IEnumerator AccessURL(string URL,AccessURLCallBack callBack)
    {
        WWW www = new WWW(URL);
        yield return www;
        if (www.error == null|| www.error=="")
        {
            //沒有錯誤
            Debug.Log("www.text=" + www.text);//文字傳輸協議—>2進位制0  1
            callBack(URL,www.bytes);
        }
        else
        {
            Debug.Log("訪問URL錯誤,錯誤是:"+www.error+",url="+URL);
        }
    }

}