I cannot use it in my code, but I see Unity’s code using it.
I haven’t ever found a need for unsafe code, but maybe this will help. Try enabling the option to “Allow ‘unsafe’ Code” in the Player Settings. Unity - Manual: Windows Player settings
Unsafe code comes in handy when you need to mess about with value types, and further usage of stuff like UnsafeUtility memory functions (besides pointers, fixed keyword also requires an unsafe context).
You can also enable unsafe code on a per-assembly-definition basis in the assembly definition’s settings. However, this isn’t what they were asking about (the System.Runtime.CompilerServices.Unsafe class, not general unsafe code).
It shouldn’t be included in the API surface Unity exposes (netstandard2.1 or netstandard2.1+net4.8) so I’m curious as to where you see them using it.
User code should be able to use the appropriate DLL from the NuGet package if necessary, provided only one copy exists in the project.
https://www.nuget.org/packages/System.Runtime.CompilerServices.Unsafe/
Note that UnsafeUtility exists in Unity and provides a number of useful methods. Unity Collections switched over to this class from using Unsafe ages ago.
https://docs.unity3d.com/ScriptReference/Unity.Collections.LowLevel.Unsafe.UnsafeUtility.html
They use it in UnsafeUtility …
// Copy from UnsafeUtility
public static ref T As<U, T>(ref U from)
{
return ref System.Runtime.CompilerServices.Unsafe.As<U, T>(ref from);
}
Are you looking at decompiled code? It doesn’t actually use Unsafe.As, but ILSpy will include Unsafe.As in the output because it’s the only way to express what the function does in C#. If you look at the actual IL, you will see that it is just ldarg.0 followed by ret.
That’s very interesting. That would explain why UnityCsReference only includes stubs for some of those UnsafeUtility methods and what kind of stuff actually goes on.