はじめに
Unity 2018.3.0b1 から C# 7.2 が使用できるようになりました
基本的には特に何も設定しなくても C# 7.2 の機能が使用できますが、
現在使用している Visual Studio のバージョンによっては
.NET SDK を追加でインストールする必要があります
Unity から Visual Studio を起動したときに、
上記のようなダイアログが表示された場合は、
赤枠をチェックして「OK」ボタンを押します
そして、上記のページがブラウザで表示されたら
「.NET Framework 4.7.1」の「Developer Pack」を選択します
そして、ダウンロードした「NDP471-DevPack-ENU.exe」を起動して
指示に従ってインストールを進めることで、Unity で C# 7.2 が使用できるようになります
C# 7.2 の機能の使用
using UnityEngine; public class Example : MonoBehaviour { readonly struct Point { public readonly int X; public readonly int Y; public Point( int x, int y ) => ( X, Y ) = ( x, y ); } void Start() { var pt = new Point( 1, 2 ); Debug.Log( pt.X + ", " + pt.Y ); } }
C# 7.2 から使用できる、readonly struct や
using UnityEngine; public class Example : MonoBehaviour { void Start() { var vec = new Vector3(); vec.Hoge(); Debug.Log( vec ); } } public static class Vector3Ext { public static void Hoge( ref this Vector3 self ) { self.x = 1; self.y = 2; self.z = 3; } }
参照渡しの拡張メソッドも問題なく使用できます