在Unity中,脚本执行的顺序是如何确定的?

huangapple go评论84阅读模式
英文:

How is the order in which scripts are executed in Unity?

问题

[![我的测试结果][1]][1]

在 Unity 中,我对在许多类中使用 `Awake()` 函数时执行顺序感到好奇,我记录了日志并看到了上面的结果。

结果是,首先生成的脚本(编号较低)会在后面执行。
但我不知道是如何或为什么会是这样……

如果可能的话,能否获得您的一些相关知识或文档链接?

附:我没有更改脚本执行顺序配置。

  [1]: https://i.stack.imgur.com/xIigB.png

public class TEST1 : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log("TEST1");
    }
}

public class TEST2 : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log("TEST2");
    }
}

public class TEST3 : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log("TEST3");
    }
}
英文:

在Unity中,脚本执行的顺序是如何确定的?

In Unity, I was curious about the sequence of execution when using Awake() function in many classes, I took a log and I could see the above results.

As a result, the scripts that were first generated, with low numbers, are executed later.
But I couldn't know How or why it is like this...

If possible, can I get some of your knowledge or URL of documents related to this?

ps. I did not change the Script Excution Order configuration.

public class TEST1 : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log("TEST1");
    }
}

public class TEST2 : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log("TEST2");
    }
}

public class TEST3 : MonoBehaviour
{
    private void Awake()
    {
        Debug.Log("TEST3");
    }
}

答案1

得分: 2

The order between scripts is intentionally indeterminate unless you specify that order in the Script Execution Order window, which has a performance penalty.

In general, the answer is: Do not assume execution order.

If you have to rely on execution order, but don't want the performance penalty of forcing it, then write in your own flags to let other scripts know when the source script is fully initialized and ready for action.

英文:

The order between scripts is intentionally indeterminate unless you specify that order in the Script Execution Order window, which has a performance penalty.

In general, the answer is: Do not assume execution order.

If you have to rely on execution order, but don't want the performance penalty of forcing it, then write in your own flags to let other scripts know when the source script is fully initialized and ready for action.

huangapple
  • 本文由 发表于 2023年2月7日 02:49:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75365430.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定