Unity WEBGL 沙箱文件

今天测试了下Unity WEBGL 平台在浏览器上运行时文件的读写问题。
代码如下:

//https://docs.unity3d.com/ScriptReference/Networking.UnityWebRequestAssetBundle.GetAssetBundle.html
            //version 用于缓存
            //using (UnityWebRequest request = UnityWebRequestAssetBundle.GetAssetBundle(url, 0, 0))
            using (UnityWebRequest request = UnityWebRequest.Get(url) )
            {
                yield return request.SendWebRequest();
                //DownloadHandlerAssetBundle downloadHandler = request.downloadHandler as DownloadHandlerAssetBundle;
                if (request.isNetworkError || request.isHttpError)
                {
                    Debug.LogErrorFormat("LoadAssetBundle error:{0}||url:{1}", request.error, url);
                }
                else
                {
                    Debug.LogFormat("LoadAssetBundle DONE:{0}", url);
                    string sandpath = Application.persistentDataPath;
                    string savepath = url.Replace(Application.streamingAssetsPath, sandpath);
                    var pos = savepath.LastIndexOf('/');
                    string dirpath = savepath.Substring(0, pos);
                    Debug.LogFormat("sand path:{0}\nsave path:{1}\ndir:{2}", sandpath, savepath,dirpath);
                    if (!Directory.Exists(dirpath))
                    {
                        Directory.CreateDirectory(dirpath);
                    }
                    try
                    {
                        File.WriteAllBytes(savepath, request.downloadHandler.data);
                    }
                    catch (Exception ex)
                    {
                        Debug.LogException(ex);
                        Debug.LogErrorFormat("文件写入失败:{0}", savepath);
                    }
                    //AssetBundle target = downloadHandler.assetBundle;
                    //AssetBundle target = DownloadHandlerAssetBundle.GetContent(request);
                    AssetBundle target = AssetBundle.LoadFromFile(savepath);
                    Debug.LogFormat("target:{0}", target);
                    callback(target);
                }
            }

测试结果发现浏览器可以下载文件并保存到本地,而且还能用直接从本地读取AssetBundle,看起来就和其他平台一样了。
进一步测试,本次下载完成并保存后下次打开文件是否还在?
结果:
下载并保存成功后刷新浏览器,文件存在。
在上一步基础上关闭浏览器并重新打开浏览器,文件存在。
清空缓存并重启浏览器,文件存在。

你可能感兴趣的:(Unity WEBGL 沙箱文件)