How to order the object initializing

Hi, I have three classes I want initialize in order. The classes are Generator, Behaviour and Player.

These 3 objects are in the scene but I don’t what is the creating order. When I execute the project It brings me an error because Behaviour is calling Generator when Generator is not created yet.

Behaviour needs Generator instance and Player needs Behaviour instance.

To solve out I kept empty the Start method of Generator and Behaviour classes.
Then, I created a new Method called Init() in both classes and I put the code to execute there.

In Player class, in the Start method, I execute:

generator = FindObjectByType(typeof(Generator));
behaviour = FindObjectByType(typeof(Behaviour));

generator.Init();
behaviour.init(generator.getMatrix());

In this way I am sure the classes are creating in the order I need.
Is this correct? Exist a better way? I know FindObjectByType is very expensive.

1 Like

Hi,
Unity Gives you power to change the order of script initialization.

Select any Script in Project View, then you would see the code in Inspector View. There is button on the top in Inspector View named “Execution Order”. In there just drag and drop your script which you want to initialize. Here you can as many as script you want to execute in what order. The Script in Higher order will execute first, followed by others. You can also play with time to execute on right side of Script in Inspector View.

Hope this helps…

1 Like

Thanks MicroEyes… I was watching that… but I have a doubt… because I have to set up a time to run the next srcipt… but I don’t know how much time the previous one needs. How much interval time do you leave between scripts?