Lately, I’ve been noticing some issues with the script execution order. It is a hit or miss sometimes. Occasionally, I’ll create an object in the level and the order is incorrect, but restarting unity fixes it.
I tried to reproduce the bug with no luck, but attached is a project package I made showing what order scripts are executed.
I noticed that you can break the order of execution by manually activating objects in the editor, although doing this through a script won’t.
On another project (much to large to upload) instantiating duplicates of an object through a script will cause the order to be broken across all the duplicates, rather than all of Component A.Start() going before all of Component B.Start() (assuming this was the order).
Try it out. It’s also useful for debugging since the messages are displayed onscreen over top of the object logging the message.
It’s not a bug, other than the script execution settings in the editor, you have no control about the execution order.
So if Object B should do something after Object A was done (i.e moved), then place your code in LateUpdate() instead of Update().
What unity do is, call all objects Update() method in the order its there in memory (it doesn’t follow a certain logic) and once it call every objects Update, it goes though all objects again and calls LateUpdate();
So you usually put camera follow code in LateUpdate() because the camera can only move, once the object it follow has been moved
@Tseng : lest Unity 3.4 allows custom script execution order (Edit > Project settings > Script Execution Order).
It is possible to configure that A.update() will be executed before B.update() during all the execution. However it is not (yet) possible to modify the order in realtime or so…
@Zergling103 : I didn’t noticed that kind of bug, but I am curious to know more about it since my current work uses SEO as backbone feature.
I’m not sure what he’s attempting to do, so it’s hard to give him guidelines. If it’s just a level initialization, he should put all of his creation code in Awake() and the rest of initialization in Start()
i.e.
If Object A depends on existence of Object B, you’ll do something like
// Object A
public class ObjectA : MonoBehaviour {
private int health;
void Awake() {
// Do dependency independent initialization here
health = 100;
}
void Start() {
}
}
// Object B
public class ObjectB : MonoBehaviour {
private int health;
private GameObject dependencyA;
void Awake() {
// Do dependency independent initialization here
health = 100;
}
void Start() {
// Do dependency dependent initialization here
dependencyA = GameObject.Find("ObjectA");
}
}
This should solve all script execution orders, where you have to dynamically obtain and assign an GameObject. Because Awake() is called when the object is instantiated and Start() is called before the first frame (after initialization) is rendered after.