Initialization and execution order
Forms that compile (7)
Section titled “Forms that compile (7)”| Syntax | Description |
|---|---|
private int V; | No initializer |
private int A = 1; | Declaration with initializer |
private int B = 2 + 3; | Initialization by expression |
private int V = Max; | Using a constant in an initializer |
private static int V = 7; | Initializing a static field |
private int[] A = new int[3]; | Initializing an array |
new Point() | Default value of a struct |
Forms that don’t compile (2)
Section titled “Forms that don’t compile (2)”| Syntax | Description | Error | Reason | Instead |
|---|---|---|---|---|
static C() { V = 7; } | Static constructor | TUKI0001 | runtime | Put it in a field initializer or Start |
[ModuleInitializer] static void Init() | Module initializer | TUKI0001 | runtime | Same as above |
| Both static constructors and module initializers assume a mechanism that runs once, when the type is first used or loaded. The runtime has nothing that triggers that one-time run. |
Put initialization in a field initializer or Start.
Field initializers
Section titled “Field initializers”No initializer
Section titled “No initializer”A field without an initializer starts at its default value (0 for int).
using UnityEngine;using Tsukimi;
public class InNoInit : TsukimiBehaviour{ void Start() { Debug.Log(V); // => 0 }
private int V;}Declaration with initializer
Section titled “Declaration with initializer”using UnityEngine;using Tsukimi;
public class InFieldOrder : TsukimiBehaviour{ void Start() { Debug.Log(B); // => 2 }
private int A = 1; private int B = 2;}Initialization by expression
Section titled “Initialization by expression”using UnityEngine;using Tsukimi;
public class InFieldExpr : TsukimiBehaviour{ void Start() { Debug.Log(B); // => 5 }
private int A = 1; private int B = 2 + 3;}Using a constant in an initializer
Section titled “Using a constant in an initializer”using UnityEngine;using Tsukimi;
public class InConstFirst : TsukimiBehaviour{ void Start() { Debug.Log(V); // => 10 }
private const int Max = 10; private int V = Max;}Initializing a static field
Section titled “Initializing a static field”using UnityEngine;using Tsukimi;
public class InStaticFieldInit : TsukimiBehaviour{ void Start() { Debug.Log(V); // => 7 }
private static int V = 7;}Initializing an array
Section titled “Initializing an array”using UnityEngine;using Tsukimi;
public class InArrayFieldInit : TsukimiBehaviour{ void Start() { Debug.Log(A.Length); // => 3 }
private int[] A = new int[3];}Default values
Section titled “Default values”Default value of a struct
Section titled “Default value of a struct”A struct created with new starts with all fields at their default values.
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 }}