You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.11 05:33:01