unity从服务器下载资源并且保存到本地

两个小功能

从服务器下载资源和资源保存到本地~

下面代码

    /// 
    /// 下载并保存资源到本地
    /// 
    /// 
    /// 
    /// 
    public static IEnumerator DownloadAndSave(string url,string name,Action Finish=null)
    {
        url = Uri.EscapeUriString(url);
        string Loading=string.Empty;
        bool b=false;
        WWW www = new WWW(url);
        if (www.error != null)
        {
            print("error:" + www.error);
        }
        while (!www.isDone)
        {
            Loading = (((int)(www.progress * 100)) % 100) + "%";
            if (Finish != null)
            {
                Finish(b, Loading);
            }
            yield return 1;
        }
       if(www.isDone)
        {
            Loading = "100%";
            byte[] bytes = www.bytes;
            b= SaveAssets(Application.persistentDataPath,name, bytes);
            if (Finish != null)
            {
                Finish(b, Loading);
            }
        }
    }

    /// 
    /// 保存资源到本地
    /// 
    /// 
    /// 
    /// 
    /// 
    public static bool SaveAssets(string path, string name, byte[] bytes)
    {
        Stream sw;
        FileInfo t = new FileInfo(path + "//" + name);
        if (!t.Exists)
        {
            try
            {
                sw = t.Create();
                sw.Write(bytes, 0, bytes.Length);
                sw.Close();
                sw.Dispose();
                return true;
            }
            catch
            {
                return false;
            }
        }
        else
        {
            return true;
        }
    }


你可能感兴趣的:(unity3d,unity3d,保存资源,下载资源)