Initializing arrays/lists

Why do you never initialize lists/arrays in the variable definition, but always in start()/awake()
For me, doing that seems like an extra inconvenient step, is there a specific reason to do it that way or is it just preference?

Thanks

In some cases it’s preference. When the list/array has the [SerializeField] attribute, Unity will initialise the list/array. Otherwise, you can decide to do it. We may want to fill that list/array with something which can’t happen at the declaration, so we end up doing it in Start or Awake anyway.

2 Likes

Sometimes it depends on your needs. Other times, it depends on your preference.

You can fill the list/array on definition.
List<string> listOfString = new List<string> { "string1", "string2", "string3 };

or you can initialise based on some sort of input later, like a FindObjectsOfType etc.

or you can do it during Start() if you’re waiting for another object to initialize before creating your data set.

others prefer to keep it in its own method to make it easier to read the code/keeping with the dry principle.

and so on.

Also as bix mentioned, the serializer can also fill the data in the list/array.

Okay, so i presume doing it on the definition has no major drawbacks then, thanks guys!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms