Back to Writing
NOTESunityunsafe-utilityperformancecsharp

Unity UnsafeUtility: Converting Enum to Int Without Boxing

September 8, 2019Updated Feb 17, 2026

Post image

In managed languages like C#, directly accessing memory is generally discouraged.

Still, there are situations where it's necessary — which is why C# provides the unsafe feature.

However, the setup is cumbersome, and without pinning memory using fixed, the runtime GC can cause issues — so caution is warranted.

I was considering pointer-based access for treating Enum values as ints. (Forced casting introduces unboxing costs that are unfavorable from both memory and performance perspectives.)

Then I discovered that Unity already provides a rich set of Unsafe utilities.

Post image

This was an unexpected but welcome find — the available functionality was exactly what I needed.

Post image

After compiling and running it myself, the results were exactly as expected.

Most of the functionality is consolidated in UnsafeUtility, which means many operations can be handled without the unsafe keyword.

That said, as the name implies, these APIs carry inherent risk — so it's important to clearly limit their scope and apply them judiciously.

UnsafeUtility is a class in the Unity.Collections.LowLevel.Unsafe namespace.


Unity - Scripting API: UnsafeUtility