Version: 2023.1
言語: 日本語
追加のクラスライブラリアセンブリの参照
スクリプティングバックエンド

C# コンパイラー

Unity プロジェクトで C# ソース コードをコンパイルするために、Unity エディターは 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
  }
}


追加のクラスライブラリアセンブリの参照
スクリプティングバックエンド
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961