Version: 2021.3
引用其他类库程序集
脚本后端

C# 编译器

为了在 Unity 项目中编译 C# 源代码,Unity Editor 使用 C# 编译器。

C# 编译器 C# 语言版本
Roslyn C# 9.0

The Editor passes a default set of options to the C# compiler. To pass additional options in your project, see the documentation on Platform Dependent Compilation.

不受支持的功能

C# 9.0

  • Suppress emitting localsinit flag
  • Covariant return types
  • Module Initializers
  • Extensible calling conventions for unmanaged function pointers
  • Init only setters

If you try to use unsupported features in your project, compilation generates errors.

Record support

C# 9 init and record support comes with a few caveats.

  • The type System.Runtime.CompilerServices.IsExternalInit is required for full record support as it uses init only setters, but is only available in .NET 5 and later (which Unity doesn’t support). Users can work around this issue by declaring the System.Runtime.CompilerServices.IsExternalInit type in their own projects.
  • You shouldn’t use C# records in serialized types because Unity’s serialization system doesn’t support C# records.

Unmanaged function pointer support

Unity supports unmanaged functions pointers as introduced in C# 9, but it doesn’t support extensible calling conventions. The following example code provides more detailed information about how to correctly use unmanaged function pointers.

The following example targets Windows platforms and requires the Allow ‘unsafe’ code to be enabled in the Player Settings menu. For more information about C#’s unsafe context, see Microsoft’s unsafe (C# Reference) documentation or Microsoft’s Unsafe code, pointer types, and function pointers documentation.


using System;
using System.Runtime.InteropServices;
using UnityEngine;

public class UnmanagedFunctionPointers : MonoBehaviour
{
  [DllImport("kernel32.dll")]
  static extern IntPtr LoadLibrary(string lpLibFileName);
  
  [DllImport("kernel32.dll")]
  static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
  
  // You must enable "Allow 'unsafe' code" in the Player Settings
  unsafe void Start()
  {
#if UNITY_EDITOR_WIN || UNITY_STANDALONE_WIN
    // This example is only valid on Windows
    
    // Get a pointer to an unmanaged function
    IntPtr kernel32 = LoadLibrary("kernel32.dll");
    IntPtr getCurrentThreadId = GetProcAddress(kernel32, "GetCurrentThreadId");

    // The unmanaged calling convention
    delegate* unmanaged[Stdcall]<UInt32> getCurrentThreadIdUnmanagedStdcall = (delegate* unmanaged[Stdcall]<UInt32>)getCurrentThreadId;
    Debug.Log(getCurrentThreadIdUnmanagedStdcall());
#endif
  }
}


引用其他类库程序集
脚本后端