MonoBehavior with readonly field initializer bad?

Usually people say a MonoBehavior should not use a default constructor and use Awake/Start instead, because it can cause problemes, for example it can be called multiple times see here: C# Constructor in MonoBehaviour - Questions & Answers - Unity Discussions

But I like to use readonly fields for example:
private readonly List _myField = new List();

I would rather not change these to Awake/Start, because they can’t be readonly anymore and I rather have them in one line.

These fields are initialized before the constructor is called, so they will also be initialized during seriaization (which can happen multiple times), but I don’t really care if some additional list instances are created during serialization. As long as there are no other issues?

Btw I have used these for years and never noticed any problem by doing so, Im just wondering if other people noticed any issues.

I think you can see some problems if you’re doing some complex code to initialize the fields.
If you’re just initializing them to a constant then there’s no problem because setting a field with the same value several time will not cause any trouble.

But if you’re initializing a field with a unique Id for example, by doing that:

_id = Interlocked.Increment(ref NextUniqueId);

Where ‘NextUniqueId’ is static, then you may have some surprises, probably some ‘holes’ in the Ids.

1 Like