error CS0103: The name 'Unsafe' does not exist - Unsafe Code in Unity

Using Unity 2020.1
OSX - Mojave
VS 8.7
All the rest is standard.

I know this has been already discussed, but I could not solve the problem.

I have some scripts that need unsafe code, but every time I end up migrating to a new system something goes wrong and I start getting this error:
error CS0103: The name ‘Unsafe’ does not exist…

Last time I solved doing a fresh project, since all the work around didn’t work for me. But now I got sucked again and the project got too big to easily migrate.

Already checked the “unsafe code” option in the player in unity.

Also tried the solutions involving creating the files: smcs.rsp file to csc.rsp, or gmcs.rsp .
It didn’t work and I also don 't get why this should help.
Deleting the library folder also didn’t help.

Someone could tell me how to solve the problem, possibly explaining how do things work?

Did you just retype that error or did you really type Unsafe? The keyword unsafe is always gonna be lowercase.

https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/unsafe

you can call something Unsafe in your comments or when you’re talking to humans, but not so much in code.

1 Like

Seriously?

Some code:

fixed (byte* target = &newBuffer[0])
Unsafe.CopyBlock(target, source, (uint)oldBuffer.Length);

Getting the same error in the Unity compiler and in the VS one.

Only thing I can think of is that you need another assembly reference, even after checking the Unsafe Code box. But this is new to me.

That’s not the keyword, that’s the class. But sure, your point is taken.

Unity’s notion of unsafe has so many strings attached when I last looked at it in 2012 (Unity3.3) that I have completely avoided it, so mark this down to TIL. This may be one of those strings. Good luck!

Could you elaborate? I still think it is odd that in Unity 2020 I’m still having this kind of problems.

Guess is already there:
using System.Runtime.CompilerServices;

Download the System.Runtime.CompilerServices.Unsafe nupkg & extract with 7zip → place the dll that can be found in lib/netstandard2.0 into your project

Note that Unity ships with its own UnsafeUtility. It comes with the UnsafeUtility.MemCpy method.

2 Likes