Documentation

Unity Engine

Download Unity

Unity Engine

BlobAssetReferenceExtensions

Extension methods for a BlobAssetReference.
Read time 2 minutesLast updated 3 hours ago

Definition

public static class BlobAssetReferenceExtensions

Remarks

A BlobAssetReference<T> doesn't keep its data alive. If you store it in a job and dispose the blob asset, the job reads freed memory. Call BlobAssetReferenceExtensions.ToBlobObjectReference to copy the blob asset into a BlobObjectReference<T> instead. The copy stays alive until you dispose the reference, so you can give it to jobs, and you can dispose the blob asset right away.
The following example uses the
Unity.Animations
,
Unity.Burst
,
Unity.Collections
,
Unity.Entities
,
Unity.Jobs
, and
UnityEngine
namespaces. It builds a custom blob asset with a
BlobBuilder
, copies it into a
BlobObjectReference
, disposes the blob asset, and reads the copy from a job.
Additional Resources: BlobObjectReference<T>

Examples

// A custom blob type, built with a BlobBuilder. It can hold only unmanaged data, such as values and BlobArray// fields.public struct MarkerTimes{ public BlobArray<float> Times;}// The job holds a BlobObjectReference, which keeps the blob alive while the job runs.// A BlobAssetReference field would point to freed memory if the blob asset were disposed first.[BurstCompile]struct SumMarkerTimesJob : IJob{ public BlobObjectReference<MarkerTimes> Markers; public NativeArray<float> Result; public void Execute() { // Keep the blob root in a ref local. A copy of a blob root can't read its blob arrays. ref MarkerTimes markers = ref Markers.Value; float sum = 0f; for (int i = 0; i < markers.Times.Length; ++i) { sum += markers.Times[i]; } Result[0] = sum; }}// Builds a blob of marker times, and returns the sum of the times, computed in a job.public static float SumMarkerTimesInJob(float[] markerTimes){ BlobObjectReference<MarkerTimes> markersReference; using (BlobBuilder blobBuilder = new BlobBuilder(Allocator.Temp)) { ref MarkerTimes root = ref blobBuilder.ConstructRoot<MarkerTimes>(); BlobBuilderArray<float> times = blobBuilder.Allocate(ref root.Times, markerTimes.Length); for (int i = 0; i < markerTimes.Length; ++i) { times[i] = markerTimes[i]; } // ToBlobObjectReference copies the blob asset, so you can dispose the blob asset right away. using BlobAssetReference<MarkerTimes> blobAsset = blobBuilder.CreateBlobAssetReference<MarkerTimes>(Allocator.Temp); markersReference = blobAsset.ToBlobObjectReference(); } using NativeArray<float> result = new NativeArray<float>(1, Allocator.TempJob); new SumMarkerTimesJob { Markers = markersReference, Result = result }.Schedule().Complete(); // Dispose the reference when no job uses it anymore. It frees the copy of the blob. markersReference.Dispose(); return result[0];}

Static Methods

Method

Description

ToBlobObjectReferenceCopies a blob asset into new blob data that a BlobObjectReference keeps alive.