Hey Community Out there, i’m Having a Question about unsafe code. What’s Happening If i’m using unsafe code and whats Happening when i use Safe Code? Is Safe Code meaning that itcIT destroy the device or so? Greetings Simon
You may need to go into a bit more detail about the code itself. Do you have examples?
Here’s the official microsoft documentation about unsafe C# code:
The basic gist I think is that unsafe contexts allow you to directly manipulate pointers, including doing pointer arithmetic and dereferencing arbitrary pointers. One reason to do this is to interact with native code that only speaks the language of pointers, rather than C#'s safer “references”.
Normally, C# can only access memory through a memory manager. It is “safe” in the sense that it will throw an exception if you have a null reference or something like that. It’s possible to handle and mitigate exception within your code if you want.
Some programming languages like C or C++ are “unsafe” in the sense that you can access memory directly. In this case if you accidentally have a null exception it may cause your program to crash entirely (possibly the Unity editor too if you are running in the editor).
Unsafe code is allowed in C# mostly for integrating with C++ or some other language that accesses memory directly. This allows you to write compatible code. The only time you’d need it in Unity is if you are trying to integrate some natively-compiled (non-C#) library, but it’s unlikely that you’ll need to do this.