Quick & Simple Question: Difference between variable instantiation

What’s the difference between instantiating a field variable on Awake() vs when you construct it.

Example:

public class TestClass : MonoBehavior
{
     int a = 0;
     int b;

    void Awake()
    {
        b = 0;
    }
}

In Unity’s case, I don’t think there is a big difference. In your example, a will have a value before Awake is called (and technically, so will b because an integer defaults to 0) because it is initialized on construction. Awake is called later. Since we don’t use the class constructors, Awake is the next best thing so there isn’t much difference IMO.

Edit There may be a difference when it comes to performance, but I think it will be minute

1 Like

For primitive types this is mostly the same. There are some corner cases (that i’m aware of) where there is a difference. For example, if you have a public variable and set its value in Awake, you will overwrite the inspector value. If you set the value directly outside of any method, the inspector value will overwrite its value instead (which you usually want).

Other than that, you can only create / access static stuff outside of method bodies. For primitive types this is fine. For objects you create (like new List()) it’s also fine. If you want to get a component from some gameobject, or something through some other reference, you will have to do that in Awake, as you cannot access non-static functions outside of methods.

1 Like