Unity WebGL中如何实现StreamingAssets资源的按需延迟加载?
WebGL项目关闭StreamingAssets预加载的实现方案
- 调整构建配置,剥离StreamingAssets主包嵌入
Unity默认会将StreamingAssets下所有内容打包到WebGL构建产物的主.data包中,启动时必须全量下载该包才会进入游戏初始化流程。你可以通过以下设置关闭该默认行为:
打开Edit > Project Settings > Player > WebGL > Publishing Settings,找到StreamingAssets配置项,勾选Do not include StreamingAssets in main data bundle(2021及以上版本支持该选项,低版本可在构建时传入BuildOptions.AdditionalStreamedResourcePaths参数指定需要剥离的StreamingAssets路径)。配置后构建时会将StreamingAssets下的文件独立输出,不会打入主包。 - 实现按需加载的异步代码
剥离后Unity不会自动预加载StreamingAssets资源,你需要自行实现异步加载逻辑(WebGL不支持同步IO操作),示例代码如下:
using UnityEngine; using UnityEngine.Networking; using System.IO; using System.Collections; public class DynamicResourceLoader : MonoBehaviour { // 需要加载资源时主动调用该方法即可 public void LoadAssetFromStreamingAssets<T>(string relativePath, System.Action<T> loadCallback) where T : Object { StartCoroutine(LoadCoroutine(relativePath, loadCallback)); } private IEnumerator LoadCoroutine<T>(string relativePath, System.Action<T> callback) where T : Object { string assetPath = Path.Combine(Application.streamingAssetsPath, relativePath); using (UnityWebRequest request = UnityWebRequest.Get(assetPath)) { yield return request.SendWebRequest(); if (request.result != UnityWebRequest.Result.Success) { Debug.LogError($"资源加载失败:{request.error},路径:{assetPath}"); callback?.Invoke(null); yield break; } // 按资源类型处理返回数据 if (typeof(T) == typeof(string)) { callback?.Invoke(request.downloadHandler.text as T); } else if (typeof(T) == typeof(Texture2D)) { Texture2D texture = new Texture2D(2, 2); texture.LoadImage(request.downloadHandler.data); callback?.Invoke(texture as T); } else if (typeof(T) == typeof(AssetBundle)) { AssetBundle bundle = AssetBundle.LoadFromMemory(request.downloadHandler.data); callback?.Invoke(bundle as T); } } } }
- 调整S3部署配置
将构建输出的独立StreamingAssets文件夹,按原目录层级上传到S3的Web应用根目录下,保证Application.streamingAssetsPath拼接相对路径后可以正确访问到S3上的资源。同时给StreamingAssets下的所有资源配置正确的CORS规则、缓存响应头Cache-Control: public, max-age=86400,避免跨域报错和重复加载浪费带宽。
注意:如果使用的Unity版本低于2020没有内置剥离选项,可以直接将原StreamingAssets目录下的内容手动移出项目,打包后作为独立静态资源上传到S3对应路径,代码中直接拼接S3资源地址加载即可达到相同效果。
内容的提问来源于stack exchange,提问作者likuku
相关产品推荐
相关产品推荐

