Skip to content

Instantly share code, notes, and snippets.

@asus4
Last active February 7, 2025 12:14
Show Gist options
  • Save asus4/914d19c8f862e7ce9dd7495af6cee2ee to your computer and use it in GitHub Desktop.
Save asus4/914d19c8f862e7ce9dd7495af6cee2ee to your computer and use it in GitHub Desktop.
Set ReadOnlySpan<T> to GraphicsBuffer in Unity
using System;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine;
namespace TheNameSpace
{
public static class GraphicsBufferExtensions
{
/// <summary>
/// Set Span to GraphicsBuffer without copying
/// </summary>
/// <param name="buffer">A GraphicsBuffer</param>
/// <param name="span">The span data to be set</param>
/// <typeparam name="T">The type of data</typeparam>
public unsafe static void SetData<T>(this GraphicsBuffer buffer, ReadOnlySpan<T> span) where T : unmanaged
{
#if ENABLE_UNITY_COLLECTIONS_CHECKS
var handle = AtomicSafetyHandle.Create();
#endif // ENABLE_UNITY_COLLECTIONS_CHECKS
fixed (void* ptr = span)
{
var arr = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray<T>(ptr, span.Length, Allocator.None);
#if ENABLE_UNITY_COLLECTIONS_CHECKS
NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref arr, handle);
#endif // ENABLE_UNITY_COLLECTIONS_CHECKS
buffer.SetData(arr);
}
#if ENABLE_UNITY_COLLECTIONS_CHECKS
AtomicSafetyHandle.Release(handle);
#endif // ENABLE_UNITY_COLLECTIONS_CHECKS
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment