Friday, November 8, 2019

Unity C# order of execution for multiple start functions?


I have a scene in my project where a lot objects need to access different objects to share data with.


Some objects have functions that need to be executed only once during the void Start function. These call a predefined function in a different class.


So now you know a bit what is happening I am experiencing an issue. During the Start function they call a method that only works when the Start function of that class has already been progressed.


Example: Class A has certain values to calculate and set. Once this has happened function A will work. Class B, C and D have a function B that is called at the last line of the Start function. Function B does some magic and then calls function A from Class A. The problem here is however that the void Start from class B, C and D executes before the Start from Class A. This results in not all values being set properly. I only discovered this through debugging and tracking timings of when each function was executed.


Is it possible for Class A to make the void Start execute before the void Start from the other classes? For example is the order of execution based on alphabetical values or something awake (per class) -> start (class A) -> start (class B) -> update (per class)? So that start A would happen before start B with a simple change of class name?


If I put this code in the awake call I will have the same issues since the awake in other classes might happen before or after the current awake will be executed.



To clarify, they all happen at the same time, but line 12 gets executed before line 13. Which is fairly logical, but how do you know which Start gets executed before the other Start? Or am I simply completely wrong?


I do realize that this might be a confusing read so please don't hesitate to ask questions so that I can explain my issue better.



Answer



Script Execution order will solve your problems, but it's also kind of a crutch and is easy to accidentally break when changing / importing project settings or refactoring code.


The biggest thing to remember is that you don't have to use the built in Monobehavior callbacks. Create a manager class with a start method, and inside that call your init methods in whatever order is necessary. This can be done with any of the execution callbacks to ensure that dependency chains are satisfied.


This also lets you break away from making everything a monobehavior and enables more flexible design options and lightweight classes / structs.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...