- Home /
class constructor/order/initialization confusion
Hi, sorry if this sounds noobish (i'm not a professional programmer), but i have the following problem: I'm about to implement a recipe system. I have two classes:
Item {
int id,
string name
and so on }
then
recipe {
int id,
item[] ingredients
}
then i have a static array:
item[] itemPresets = {
new item(X, xx,...),
new item(Y, yy,...)
}
now i need something like these itempresets for the recipes too. But the constructor for the recipe class is:
Recipe(int _id, int item1, int item2){
id = _id;
ingredients[0] = itemPresets.GetItemByID(item1);
and so on..
}
i need these as ints because i have to be able to send them via RPC too. But:
how can i be sure, that "itemPresets" is initialized first so "GetItemByID" returns the right item?
Or am i doing something really wrong here? Are there some "best practices" for this?
Thank you for your time. (and sorry, if i misspelled something, english is not my native tongue)
Answer by Michael CMS · Nov 01, 2012 at 09:45 PM
You can be sure that statics arrays are initialized before the constructor code.
Blockquote 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. Blockquote
Hope this helps
sorry, i'm still confused. So the compiler can figure out which array needs to be filled first by analyzing the code, even though i initialize it with help of a function which in return needs access to an already initialized array? (i googled a bit for static field initialization after your comment, but i'm not really sure if this is what i mean). I have to say i dont initialize it in Start() or Awake but varray = {Xobject,Xobject}. Should i do it in Start to have more control?
The compiler doesn't figure out which array needs to be filled first. It just initializes them in the order you declare them in your code.
If you have for example : A[] = {xObj(),xObj()}; B[] = {yObj(),yObj()};
Then A will be initialized by the time B starts initializing.
xObj's constructor won't have either A or B initialized, while yObj's constructor will have only A initialized
Switching the order of the declaration of A and B will reverse their initialization order also.
Ofc if you feel more comfortable you can move the code in the Start /Awake functions.
Thank you. Good to know. And, now I did move it to Start(); that felt right and it works.
Your answer
Follow this Question
Related Questions
What the best way to initialize constant static data in a MonoBehavior? 0 Answers
Static GameObject List gives error when calling Add or Count from another script 1 Answer
Using static constants from an outside script 2 Answers
Error Assigning GameObject To Var Inside A Class 3 Answers
Auto Commenting lines 1 Answer