初期化と実行順序
書ける形(7)
Section titled “書ける形(7)”| 書き方 | 説明 |
|---|---|
private int V; | 初期化子なし |
private int A = 1; | 宣言と同時の代入 |
private int B = 2 + 3; | 式による初期化 |
private int V = Max; | 初期化子での定数の利用 |
private static int V = 7; | 静的フィールドの初期化 |
private int[] A = new int[3]; | 配列の初期化 |
new Point() | struct の既定値 |
書けない形(2)
Section titled “書けない形(2)”| 書き方 | 説明 | エラー | 理由 | 代わりに |
|---|---|---|---|---|
static C() { V = 7; } | 静的コンストラクタ | TUKI0001 | 環境 | フィールドの初期化子か Start に置く |
[ModuleInitializer] static void Init() | モジュール初期化子 | TUKI0001 | 環境 | 同上 |
| 静的コンストラクタもモジュール初期化子も、型を最初に使うときや読み込みのときに 1 回だけ走ることを前提にした仕組みです。実行環境には、その 1 回を起こす側がありません。 |
初期化は、フィールドの初期化子か Start に置きます。
フィールドの初期化子
Section titled “フィールドの初期化子”初期化子なし
Section titled “初期化子なし”初期化子を書かないフィールドは、既定の値(int なら 0)で始まります。
using UnityEngine;using Tsukimi;
public class InNoInit : TsukimiBehaviour{ void Start() { Debug.Log(V); // => 0 }
private int V;}宣言と同時の代入
Section titled “宣言と同時の代入”using UnityEngine;using Tsukimi;
public class InFieldOrder : TsukimiBehaviour{ void Start() { Debug.Log(B); // => 2 }
private int A = 1; private int B = 2;}式による初期化
Section titled “式による初期化”using UnityEngine;using Tsukimi;
public class InFieldExpr : TsukimiBehaviour{ void Start() { Debug.Log(B); // => 5 }
private int A = 1; private int B = 2 + 3;}初期化子での定数の利用
Section titled “初期化子での定数の利用”using UnityEngine;using Tsukimi;
public class InConstFirst : TsukimiBehaviour{ void Start() { Debug.Log(V); // => 10 }
private const int Max = 10; private int V = Max;}静的フィールドの初期化
Section titled “静的フィールドの初期化”using UnityEngine;using Tsukimi;
public class InStaticFieldInit : TsukimiBehaviour{ void Start() { Debug.Log(V); // => 7 }
private static int V = 7;}配列の初期化
Section titled “配列の初期化”using UnityEngine;using Tsukimi;
public class InArrayFieldInit : TsukimiBehaviour{ void Start() { Debug.Log(A.Length); // => 3 }
private int[] A = new int[3];}struct の既定値
Section titled “struct の既定値”new で作った struct は、すべてのフィールドが既定の値で始まります。
using UnityEngine;using Tsukimi;
public struct Point { public int X; }public class InStructDefault : TsukimiBehaviour{ void Start() { Point p = new Point(); Debug.Log(p.X); // => 0 }}