使用UnityWebRequest时如何正确搭配File.WriteAllBytes保存文件?
UnityWebRequest读取StreamingAssets文件并存储解决方案
误区修正
UnityWebRequest.bytes属性并未被官方标记为过时,你遇到的报错通常由以下原因导致:
- 拼写错误:你注释中写的
donwloader为拼写错误,少了字母l - 未做请求状态校验:请求失败时直接读取
bytes会触发异常 - 冗余等待逻辑:
yield return downloader.SendWebRequest()已经会等待请求执行完成,不需要额外加while (!downloader.isDone)循环
修正后可运行代码
#if UNITY_ANDROID using UnityEngine.Networking; using System.IO; // 该逻辑需要放在IEnumerator协程方法内 string sourcePath = Path.Combine(Application.streamingAssetsPath, "game.dat"); string dataFilePath = Path.Combine(Application.persistentDataPath, "game.dat"); UnityWebRequest downloader = UnityWebRequest.Get(sourcePath); yield return downloader.SendWebRequest(); // 先校验请求是否成功 if (downloader.result == UnityWebRequest.Result.Success) { // File.WriteAllBytes第二个参数直接传入请求返回的字节数组即可 File.WriteAllBytes(dataFilePath, downloader.bytes); } else { Debug.LogError($"读取文件失败:{downloader.error}"); } downloader.Dispose(); #endif
注意事项
- 执行该逻辑的方法必须声明为
IEnumerator类型,通过StartCoroutine调用 - 确保
game.dat文件已经放在项目根目录下的StreamingAssets文件夹内,打包时会被正确打进包体 - 首次存储完成后,后续读取可以直接从
Application.persistentDataPath路径读取,不需要再次从StreamingAssets复制
内容的提问来源于stack exchange,提问作者hello world
相关产品推荐
相关产品推荐

