hey! just wondering… is there any difference to defining a new list like this:
“private List< Unit > unitList = new List< Unit >();”
as apposed to this: “private List< Unit > unitList;” and then in the awake (or in this case in the constructer): "unitList = new List< Unit >(); " ?
thanks!
Not really, the only difference is when these are created. But if we are talking about the constructor, the ‘when’ is minimal. In the first one - private List<Unit> unitList = new List<Unit>();
- the list is created before the constructor is called. In the second one it is - obviously - created when the constructor is called. It doesn’t really matter because the constructor is usually executed immediately after. With Awake
it’s a little different because something (another Awake
) may want to access that list before the containing component’s Awake
was called. These are ‘race conditions’ which may cause issues further down the line, though
so if i understand, either would work in almost any situation (except for “racing” cases)… thanks!
As a rule of thumb, I strongly recommend using the = initializer with all List and Dictionary declarations.
- No harm is done if Awake() creates a new list anyways, the initialized one just gets garbage collected
- One of the most common null reference errors occurs when a global List is declared, but never initialized.
thanks! so i should use: private List< Unit > unitList = new List< Unit >(); instead of on defining on start or awake… thanks!
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.