NativeArrays
Read time 5 minutesLast updated 14 days ago
NativeArrays and other types in the Unity.Collections namespace store data in memory that isn't managed by the scripting runtime. When you pass a pointer to this data to native code, you don't have to "pin" the buffer in memory. However, you still need to consider the memory lifetime of the data, which is determined by the Allocator you use:
Allocator | Lifetime | Typical memory pool size |
|---|---|---|
| Allocator.Temp | The memory is automatically cleaned up at the end of each frame. | 4-16 MB main thread 256 KB worker threads |
| Allocator.Persistent | The memory persists until the object that owns the allocation is disposed of. | |
| Allocator.Domain | The memory persists until the C# domain is unloaded. | |
| Allocator.TempJob | The memory persists until the object that owns the allocation is disposed of. TempJob allocations shouldn't be kept for more than four frames. If this type of memory is exhausted, then Unity falls back to a slower memory allocation method. | 16-64 MB |
| Allocator.None | The None allocator is used when the instance does not own the memory in the buffer it references. |
Allocator.TempThe layout of a NativeArray struct is an internal detail, so you can't control how its fields are marshalled. However, you can pass a pointer to the buffer inside the array using an explicit pointer in an unsafe context.
Use unsafe to get an array pointer
Use the method or the NativeArrayUnsafeUtility class to get a pointer to the buffer in a NativeArray. When you pass the pointer to an unmanaged function, you can treat it like a C array.
NativeArray.GetUnsafePtr()The following example is an unmanaged function that takes an array of (unsigned 32-bit integers) as a parameter:
Colortypedef int32_t Color;extern "C" { void CheckerFill(Color* texture, int width, int height, int numSquares, const Color colors[], int numColors) { const int squareSize = width / numSquares; for (int y = 0; y < height; ++y) { for (int x = 0; x < width; ++x) { // Select a palette entry, staying within the bounds of the colors array const int colorIndex = ((y / squareSize) + (x / squareSize)) % numColors; texture[y * width + x] = colors[colorIndex]; } } }}
You can pass a pointer to a NativeArray's buffer to this function. Using pointers in C# requires an unsafe context. Refer to Compiling unsafe C# code for information about enabling code compilation in Unity.
unsafeThe following code demonstrates how to call the unmanaged function. The example performs the following steps:
CheckerFill()- Gets a NativeArray containing the pixel data of a Texture2D object.
- Gets a pointer to the NativeArray's buffer with .
GetUnsafePtr() - Calls the unmanaged, , function to fill the texture with a checker pattern.
CheckerFill() - Applies the result to the Texture2D object.
using UnityEngine;using Unity.Collections;using System.Runtime.InteropServices;using Unity.Collections.LowLevel.Unsafe;public class NativeArrayExamples{ // Change DllImport to use library name for // precompiled, dynamically linked libraries. [DllImport("__Internal")] static extern unsafe void CheckerFill(Color32* pixelDataPtr, int width, int height, int squares, [In] Color32[] colors, int numColors); public static void FillTextureWithCheckerboard(Texture2D texture, Color32 one, Color32 two, int squaresPerSide) { unsafe { // Get the pixel data as a NativeArray NativeArray<Color32> pixelData = texture.GetPixelData<Color32>(0); // Get a pointer to the NativeArray's buffer void* pixelBuffer = pixelData.GetUnsafePtr(); // The color palette to choose from var palette = new Color32[] { one, two }; // Call the unmanaged function, passing the palette length so it stays within the colors array CheckerFill((Color32*)pixelBuffer, texture.width, texture.height, squaresPerSide, palette, palette.Length); // Apply the changes to the texture texture.Apply(false); } }}
Demonstration
You can use the following MonoBehaviour class to call the NativeArrayExamples FillTextureWithCheckerboard method. The example adds two GameObject primitives to the scene with textures generated using the unmanaged CheckerFill function.
using UnityEngine;public class DemoNativeArray : MonoBehaviour{ void Start() { AddCheckeredObject(PrimitiveType.Sphere, Color.blue, Color.yellow, Vector3.zero); AddCheckeredObject(PrimitiveType.Cube, Color.red, Color.white, Vector3.one); } void AddCheckeredObject(PrimitiveType primitive, Color colorOne, Color colorTwo, Vector3 position) { // Create a new texture Texture2D checkerboard = new Texture2D(256, 256, TextureFormat.RGBA32, false); // Fill the texture with a checkerboard pattern using the NativeArrayExamples class NativeArrayExamples.FillTextureWithCheckerboard(checkerboard, colorOne, colorTwo, 8); var go = GameObject.CreatePrimitive(primitive); go.transform.position = position; var litShader = Shader.Find("Universal Render Pipeline/Lit"); if (litShader != null) { // Create a new material using the URP Lit shader Material material = new Material(litShader); // Assign the texture to the material material.SetTexture("_BaseMap", checkerboard); go.GetComponent<MeshRenderer>().material = material; } else Debug.LogError("Unable to load the Universal Render Pipeline/Lit shader."); }}
Notes:
- The example requires IL2CPP and doesn't work in the Editor Play mode when you use . To run the example in Play Mode, you can compile the unmanaged example code as a library and change the
[DllImport("__Internal")]statements to use the library name. Refer to DllImport attribute for more information.DLLImport - The demonstration loads the URP Lit shader at runtime. The build process strips unused shaders and variants from a build, and can't detect runtime usage such as this. The easiest workaround to run this example is to add a primitive object to the scene before building.
- returns a NativeArray that points to the texture's existing memory. It doesn't allocate memory, so you don't need to dispose the NativeArray. (Disposing it doesn't do anything.)
Texture2D.GetPixelData<T>