Execution order and compilation order of scripts in Unity3d (VS Engineering reference relationships)

Source: Internet
Author: User

From: http://www.cnblogs.com/champ/p/execorder.html

In unity, you can create many scripts at the same time, and you can bind to different game objects individually, each of which runs in its own life cycle. The script is about compiling and executing, and this article is going to look at the compilation and execution order of the scripts in unity.

Order of execution of event functions

Let's talk about the order of execution first.
The order in which the event functions are executed in the official script is as follows:

We can do a little experiment to test it:
Create three game objects in the hierarchy view, create three scripts in Project view, as shown in, and then bind the script to the corresponding game object in order:


The code for the three script is exactly the same, just a little bit of a name distinction:

1234567891011121314151617181920212223242526272829 usingUnityEngine;using System.Collections;publicclassScring0 : MonoBehaviour{    voidAwake()    {        Debug.Log("Script0 ======= Awake");    }    boolisUpdate = false;    voidUpdate()    {        if(!isUpdate)        {            Debug.Log("Script0 ======= Update");            isUpdate = true;        }    }    boolisLateUpdate = false;    voidLateUpdate()    {        if(!isLateUpdate)        {            Debug.Log("Script0 ======= LateUpdate");            isLateUpdate = true;        }    }}

Play the game and see the order in which they are executed. As shown, awake, Update, lateupdate, regardless of the number of times the game is run, the order in which they are executed is exactly the same.

Then we do a test, the Script0 Update method commented out!!

123456789101112131415161718192021222324252627282930 usingUnityEngine;usingSystem.Collections;publicclassScript0 : MonoBehaviour {     void Awake ()     {        Debug.Log("Script0 ========= Awake");    } //  bool isUpdate = false;//  void Update () //  {//      if(!isUpdate)//      {//          Debug.Log("Script0 ========= Update");//          isUpdate = true;//      }//  }     boolisLateUpdate = false;    voidLateUpdate()    {        if(!isLateUpdate)        {            Debug.Log("Script0 ========= LateUpdate");            isLateUpdate = true;        }    }}

Run the game again to see its results. The script executes in exactly the same order as before, Script0 even if the update method is removed, but it does not execute the Lateupdate method directly, but waits for the Update method in both SCRIPT1 and Script2 to finish executing. Then execute all the lateupdate methods.


With these two examples, we can clearly determine how the unity daemon executes the script. Each script awake, Start, Update, Lateupdate, Fixedupdate, and so on, all of the methods are rolled up in the background:

1234567 后台的Awake(){    // 这里暂时按照中的脚本执行顺序,后面会谈到其实可以自定义该顺序的    脚本2中的Awake();    脚本1中的Awake();    脚本0中的Awake();}

Backstage methods Awake, update, lateupdate and so on, are in accordance with the order, and so on all the game objects on the script awake execution, then go to start, update, Lateupdate and other methods.

1234567 后台的Update(){    // 这里暂时按照中的脚本执行顺序,后面会谈到其实可以自定义该顺序的    脚本2中的Update();    脚本1中的Update();    脚本0中的Update();}
Execution order of scripts

Then let's look at a scenario where you create a cube object in the Awake method of script 0, and then get the cube object in the Awake method of script 2. The code is as follows:

12345678910111213141516171819202122 // Script0.csusingUnityEngine;usingSystem.Collections;publicclassScript0 : MonoBehaviour {    voidAwake ()    {        GameObject.CreatePrimitive(PrimitiveType.Cube);    }}// Script2.csusingUnityEngine;usingSystem.Collections;publicclassScript2 : MonoBehaviour {    voidAwake ()     {        GameObject go = GameObject.Find("Cube");        Debug.Log(go.name);    }}

If the execution order of the script is to execute SCRIPT0 first and then execute SCRIPT2, then awake in Script2 can get to the cube object correctly, but if the script executes Script2 first, then Script0, Then the SCRIPT2 will certainly report a null pointer error.

So there are a lot of scripts in the actual project, and the order of their execution is not known to us (some say it is done according to the stack structure, that is, the script that binds to the game object executes first.) This can be obtained from the above example, but the official does not say so, and it has to be further studied in depth. However, in general, it is recommended that you create a game object or Resources.load (Prefab) object in the Awake method, and then get the game object or component in the Start method, because the order of execution of the event functions is fixed, so that it is foolproof.
In addition, Unity provides a way to set the order in which scripts are executed, which you can see in the Inspector panel in the Script Execution Order menu item, edit-Settings:

Clicking on the "+" in the lower right corner will bring up the drop-down window, including all the scripts in the game. After the script is added, you can use the mouse to drag the script to sort the script, the smaller the number behind the name of the foot, the more the script, the more the first execution. The default time in it indicates the order in which scripts are executed without setting the execution order of the scripts.

According to the diagram above, let's look at the output of the console to make sure our settings work (note: Uncomment the Update method in the Script0 script):

Compilation Order of scripts

The compilation order of the script is a headache, the official statement is a bit vague, see the official explanation:

Because the compilation order of scripts involves special folders, such as the plugins, editor, and standard assets, which are mentioned above, the location of the script is very important. Here is an example of the compilation order of scripts in different folders:

In fact, if you are careful, you will find that if you build the folder hierarchy as shown in your project, the project files will be generated in the project folder after compiling the project file with the words editor and Firstpass in the file name. For example, according to the folder structure, we open the project folder to see what the resulting project file is?

What do you mean by discussing these words in detail? How do they relate to the order in which the scripts are compiled?

1, first from the scripting language type, Unity3d support 3 scripting languages, will be compiled into the CLI DLL

If the project contains C # scripts, then Unity3d will produce a project prefixed with Assembly-csharp, with the name "vs" generated for Vistual studio, and not "vs" generated for MonoDevelop.

scripting language in the project Project Prefix Project suffix
C# Assembly-csharp Csproj
Unityscript Assembly-unityscript Unityproj
Boo Assembly-boo Booproj

If all three of these scripts exist in the project, unity will generate 3 types of prefix-type projects.

2, for each scripting language, according to the location of the script placement (in fact, in part according to the role of script, such as editor extension script, must be placed in the Editor folder), unity will generate 4 suffix of the project. The firstpass means to compile first, and editor to represent the script placed under the Editor folder.

In the example above, we got two project engineering files: used by Virtual studio and MonoDevelop (suffix package does not contain vs), for simplicity, we only analyze vs projects. The resulting file list is as follows:
Assembly-csharp-filepass-vs.csproj
Assembly-csharp-editor-filepass-vs.csproj
Assembly-csharp-vs.csproj
Assembly-csharp-editor-vs.csproj

According to the official explanation, they are compiled in the following order:
(1) All scripts in standard Assets, Pro standard Assets, or plugins folder generate a assembly-csharp-filepass-vs.csproj file and compile it first;
(2) All in standard Assets/editor, Pro standard assets/editor or plugins/ The script in the Editor folder produces the Assembly-csharp-editor-filepass-vs.csproj project file, which is then compiled;
(3) All the script files outside the Assets/editor and not in (1), (2) (usually these scripts are the non-editor extension scripts that we write ourselves) will produce the Assembly-csharp-vs.csproj project file and be compiled;
(4) All scripts in Assets/editor produce a assembly-csharp-editor-vs.csproj project file, which is compiled.

The reason for building the project in this order and compiling it in this sequence is also determined by the dependencies that exist between the DLLs.

Well, so far, we can easily determine the order in which the scripts are compiled in the example above (in fact, I've written the order in the script's file name)

Little Practice

How many engineering documents can be produced in a Unity3d project?

4*3*2=24

Written in the last words

The articles referenced above are:
1. Unity3d Research Institute's in-depth understanding of the execution order of Unity Scripts (62)
2. Comprehensive parsing of Unity3d automatically generated script engineering files

Project Reference Relationship:

(go) execution order and compilation order of scripts in Unity3d (VS Engineering reference relationships)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.