为了在 Unity 项目中编译 C# 源代码,Unity Editor 使用 C# 编译器。
| C# 编译器 | C# 语言版本 |
|---|---|
| Roslyn | C# 9.0 |
Editor 会将一组默认选项传递给 C# 编译器。要在项目中传递其他选项,请参阅有关平台相关的编译的文档。
如果尝试在项目中使用不受支持的功能,则编译会产生错误。
C# 9 中的初始化和记录支持附带一些注意事项。
System.Runtime.CompilerServices.IsExternalInit 是实现完整记录支持所必需的,因为它只使用了仅初始化设置器,但仅在 .NET 5 及更高版本中可用(而 Unity 不支持这些版本)。用户可以通过在自己的项目中声明 System.Runtime.CompilerServices.IsExternalInit 类型来解决此问题。Unity 支持 C# 9 中引入的非托管函数指针,但不支持可扩展调用约定。以下示例代码提供了有关如何正确使用非托管函数指针的更多详细信息。
以下示例针对 Windows 平台,要求在播放器设置 (Player Settings) 菜单中启用允许“不安全”代码 (Allow ‘unsafe’ code)。有关 C# unsafe 上下文的更多信息,请参阅 Microsoft 的不安全 (C# 参考)文档或 Microsoft 的不安全代码、指针类型和函数指针文档。
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
}
}