AssetBundle.LoadFromStreamAsync

Switch to Manual
public static AssetBundleCreateRequest LoadFromStreamAsync (Stream stream, uint crc= 0, uint managedReadBufferSize= 0);

Parameters

stream 托管 Stream 对象。Unity 调用 Read()、Seek() 和该对象的 Length 属性来加载 AssetBundle 数据。
crc 未压缩内容的 CRC-32 校验和(可选)。
managedReadBufferSize 加载数据时使用的读取缓冲区大小(可选)。默认大小为 32KB。

Returns

AssetBundleCreateRequest AssetBundle 的异步创建请求。加载后使用 assetBundle 属性获取 AssetBundle。

Description

从托管 Stream 异步加载 AssetBundle。

该函数支持任意压缩类型的捆绑包。 如果是 lzma 压缩数据,则将数据解压缩到内存。如果是未压缩或使用块压缩的捆绑包,则直接从 Stream 读取。

LoadFromStream 不同,该函数是异步的。

LoadFromFileAsync 不同的是,AssetBundle 的数据由托管 Stream 对象提供。

以下是对 Stream 对象的限制,以优化 AssetBundle 数据加载:
1. The AssetBundle must start at stream position zero.
2.在加载 AssetBundle 数据前,Unity 将搜寻位置设置为零。
3. Unity assumes the read position in the stream is not altered by any another process. This allows the Unity process to read from the stream without having to call Seek() before every read.
4.stream.CanRead 必须返回 true。
5.stream.CanSeek 必须返回 true。
6. It must be accessible from threads different to the main thread. Seek() and Read() can be called from any Unity native thread.

加载 AssetBundle 或从捆绑包中加载任何资源时,不要处置 Stream 对象。其生命周期应该比 AssetBundle 长。也就是说,您应该先调用 AssetBundle.Unload,而后处置 Stream 对象。


using UnityEngine;
using System.Collections;
using System.IO;
using System;

public class LoadFromFileAsyncExample : MonoBehaviour { IEnumerator Start() { var fileStream = new FileStream(Application.streamingAssetsPath, FileMode.Open, FileAccess.Read); var bundleLoadRequest = AssetBundle.LoadFromStreamAsync(fileStream); yield return bundleLoadRequest;

var myLoadedAssetBundle = bundleLoadRequest.assetBundle; if (myLoadedAssetBundle == null) { Debug.Log("Failed to load AssetBundle!"); yield break; }

var assetLoadRequest = myLoadedAssetBundle.LoadAssetAsync<GameObject>("MyObject"); yield return assetLoadRequest;

GameObject prefab = assetLoadRequest.asset as GameObject; Instantiate(prefab);

myLoadedAssetBundle.Unload(false); } }