At the beginning, one of the most confusing thing in programming in Unity is its architecture. This architecture based on components so programmers who create ‘standard’ structural applications may find this approach a little strange. Everything seems to be ‘parallel’ and does not have specified start and end. It needs time to get used to this way of games development. Today we will show you how to change execution order in Unity!
The most important thing is to look at Script lifecycle which can be found here: Execution order – Script lifecycle. In a nutshell:
- GameObjects in the scene can have scripts,
- scripts have methods which are invoked in proper time by game engine (for example: all Start methods procede all Updates),
- execution order of one ‘type’ of methods between all scene’s objects is determined by their load time,
- scripts are execute in arbitraty order.
Now, we have one question. What if we want to run one or more scripts before others? There are two exemplary scenarios: we want to execute fuction before the game starts; we want to force executing one script before others. We prepared simple package with some scripts and objects to check in practice how Unity works. You can download it here: Download. Create empty Unity project and load Test scene. When you run it you will see:
This package contains 4 scripts:
- CommonScript – MonoBehaviour script which contains simple Awake, Start and Update methods,
- NormalExecutionOrder – script which inherits from CommonScript and is used to execute in default order,
- CustomExecutionOrder – script which also inherits from CommonScript but this one is used in changed execution order,
- FirstAwakeScript – implements only Awake method which should be executed before others.
FirstAwakeScript and CustomExecutionOrder have different execution times (values -200 and -100 means that they scripts will be executed before other scripts; these values are just order indicators). As you can see in Console, Awake method in FirstAwakeScript is always the first. Object3 which contains CustomExecutionOrder script attached has precedense over other objects.
Remember to save all changes in execution order by hitting Apply button. Also remember that changing execution order can be very useful but it can lead to many hard to grasp errors.
We recommend to not rely on script execution order between objects. If your game needs to use some critical parts where order of execution is crucial, consider creating more complex scripts controller which can execute functions between scripts in proper order. Noone wants to create random behaving game 😉
It’s all for now. Next week we are going to prepare something special for you so be prepared! 🙂
Aliasing Games Team!