GuardHei
GuardHei

Reputation: 13

Fail to initiate static variables in c# of Unity

I was trying to make a singleton in Unity 2017.

public class Singleton {

    public static readonly Singleton instance = new Singleton();

    static readonly float FLOAT_VAL = 3.5f;
    static readonly int INT_VAL = 3;

    private Singleton() {
        Debug.Log("FLOAT_VAL = " + FLOAT_VAL);
        Debug.Log("INT_VAL = " + INT_VAL);
    }
}

I expected to see the output of "FLOAT_VAL = 3.5" and "INT_VAL = 3". However, it came out with the output of "FLOAT_VAL = 0" and "INT_VAL = 0". Then I deleted both "readonly" modifiers, leaving "static" and still got two zero.

What happened to the initiation or construction of this singleton? How can I correctly give the values to the static variables? Is there anything to do with Unity? (I chose il2cpp when building the project, but this was tested under Editor Mode)

By the way, I figured out that the initiation of the variable "instance" didn't start until the first call (I used to think that all static vars get initialized when the assembly is loaded.). Is it also another Unity feature or just normal?

Upvotes: 1

Views: 779

Answers (3)

Sweeper
Sweeper

Reputation: 271070

From the C# language specification

§10.5.5.1

Static field initialization

The static field variable initializers of a class correspond to a sequence of assignments that are executed in the textual order in which they appear in the class declaration. If a static constructor (§10.12) exists in the class, execution of the static field initializers occurs immediately prior to executing that static constructor.Otherwise, the static field initializers are executed at an implementation-dependent time prior to the first use of a static field of that class.

So basically, because you wrote instance first, it is initialised before FLOAT_VAL and INT_VAL. Reverse the order and you will see your expected results:

public class Singleton {


    static readonly float FLOAT_VAL = 3.5f;
    static readonly int INT_VAL = 3;


    public static readonly Singleton instance = new Singleton();

    private Singleton() {
        Console.WriteLine("FLOAT_VAL = " + FLOAT_VAL);
        Console.WriteLine("INT_VAL = " + INT_VAL);
    }
}

Upvotes: 1

buffalo94
buffalo94

Reputation: 159

If your class contains static fields, provide a static constructor that initializes them when the class is loaded.[MSDN]

Add a static constructor to initialize your static variables

Upvotes: -1

Keith Nicholas
Keith Nicholas

Reputation: 44288

The fields get initialized in the order they are declared.... so since your instance comes first, your other values are zero. If you move them above your instance they will have the values you expect

Upvotes: 2

Related Questions