Skip to content

Commit 2cfbb16

Browse files
committed
reducing memory alloc for texture loading from non-memory streams (also fixes temp.memalloc warnings)
1 parent a8037c8 commit 2cfbb16

1 file changed

Lines changed: 18 additions & 2 deletions

File tree

Runtime/Scripts/SceneImporter/ImporterTextures.cs

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -550,9 +550,25 @@ protected virtual async Task ConstructUnityTexture(Stream stream, bool markGpuOn
550550

551551
stream.Read(buffer, 0, (int)stream.Length);
552552
await YieldOnTimeoutAndThrowOnLowMemory();
553-
using (NativeArray<byte> bufferNative = new NativeArray<byte>(buffer, Allocator.TempJob))
553+
554+
NativeArray<byte> nativeBuffer;
555+
ulong gcHandle;
556+
unsafe
557+
{
558+
559+
var ptr = UnsafeUtility.PinGCArrayAndGetDataAddress(buffer, out gcHandle);
560+
nativeBuffer = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<byte>(ptr, buffer.Length, Allocator.None);
561+
#if ENABLE_UNITY_COLLECTIONS_CHECKS
562+
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref nativeBuffer, AtomicSafetyHandle.GetTempMemoryHandle());
563+
#endif
564+
}
565+
try
566+
{
567+
texture = await CheckMimeTypeAndLoadImage(image, texture, nativeBuffer, markGpuOnly, isLinear);
568+
}
569+
finally
554570
{
555-
texture = await CheckMimeTypeAndLoadImage(image, texture, bufferNative, markGpuOnly, isLinear);
571+
UnsafeUtility.ReleaseGCObject(gcHandle);
556572
}
557573
}
558574

0 commit comments

Comments
 (0)