Blob asset
前言
Blob asset用于存储二进制数据,且为不可变数据。适合那种整个游戏只需要一份数据且不会改变的情况下使用,比如一些资源类的数据。
一、Blob asset使用
利用BlobAssetReference来访问blobAsset。
注意点:1.blobAsset的数据定义在Component外,然后通过BlobAssetReference引用来访问,如下所示:
struct MarketData
{
public float PriceOranges;
public float PriceApples;
}
BlobAssetReference<MarketData> CreateMarketData()
{
// Create a new builder that will use temporary memory to construct the blob asset
var builder = new BlobBuilder(Allocator.Temp);
// Construct the root object for the blob asset. Notice the use of `ref`.
ref MarketData marketData = ref builder.ConstructRoot<MarketData>();
// Now fill the constructed root with the data:
// Apples compare to Oranges in the universally accepted ratio of 2 : 1 .
marketData.PriceApples = 2f;
marketData.PriceOranges = 4f;
// Now copy the data from the builder into its final place, which will
// use the persistent allocator
var result = builder.CreateBlobAssetReference<MarketData>(Allocator.Persistent);
// Make sure to dispose the builder itself so all internal memory is disposed.
builder.Dispose();
return result;
}
2.blob中能够存储是数据类型:
存储值类型数据。
Blitable Type数据。
以及额外的:BlobArray, BlobPtr, and BlobString三种特殊数据。
3.如果是BlobArray, BlobPtr, and BlobString三种特殊数据,则除了builder.ConstructRoot初始化内存外,还需要使用对应的接口来分配内存使用。详细可以看官方文档的示例:
官方BlobAsset使用示例
核心就是用Allocate给BlobArrary数组对象分配内存;AllocateString给字符串对象分配内存;SetPointer给BlobPtr设置指针引用(相对地址的)。
4.最后一定要记得手动dispose不用的blobAsset对象。额外的,如果是从场景中随Entity Bake出来的BlobAsset,不需要手动dispose,它会随场景一起销毁释放。
5.除了可以把BlobAssetReference数据放到Component中去外,还可以直接用AddBlobAsset将BlobAssetReference添加到对应的Entity上。