问题描述
直到现在,我一直在编码,认为monobehaviour
中的函数将按以下顺序执行:
Until now, I've been coding thinking that functions in monobehaviour
would be executed in this order:
问题在于我认为该顺序是绝对,这意味着在一个函数没有完全完成之前,就不可能开始执行下一个函数.
The problem is that I thought that this order would be absolute, meaning that until a function is not completely finished, there's no way that the next one would start being executed.
- 第一个问题是:是这样吗?直到
start
结束,才会执行update
吗?
- So first question is: Is that true? Would
update
NOT be executed untilstart
ends?
然后我的问题出现在不同的monobehaviour
类之间的同步上.
Then my problem arises with synchronization between different monobehaviour
classes.
我有一个在其start
函数中创建一些对象(基本上是菜单)的类.然后在另一个类中,我有一个类似的代码,但是它也依赖,它依赖于第一个类创建的对象已经存在.我收到错误消息,因为尚未找到对象.
I have a class that creates some objects (a Menu basically) in its start
function. Then in a different class, I've a similar code, but it also depends on the object created by the first class to exist already. I'm getting an error because the object is not found yet.
所以现在我被困住了.因此,我的第二个问题是,
So now I'm stuck with this. Therefore my second question would be,
- 当我的不同班级依赖其他人时,如何同步我的班级?
最后,还必须问这两个问题:
Finally, a question mixed from these two also has to be asked:
-
update
函数是否可以在这些类中的任何一个中执行,而它们却以某种方式等待"其初始化部分,无论是在start
函数,OnEnable
函数中还是在其他任何类中?
- Would
update
function be executed in any of these classes, while they're somehow "waiting" for their initialization part, be it instart
function,OnEnable
function or whatever?
当然,由于update
函数依赖于已初始化的对象,因此可能会导致新的问题.
Because of course, update
function relies on objects being initialized already, and this could end in new problems.
预先感谢
推荐答案
很难说问题的真正出处,因为您尚未发布任何代码.但是,我相信您可以通过实施2
It is hard to say where your problem is actually coming from, because you have not posted any code. However, I believe your problem might be solved by implementing solution noted at 2
-
是的,如果启用/激活了游戏对象/单行为,则在更新功能之前调用所有开始功能"(和唤醒")!未激活的游戏对象上不会调用开始/唤醒/更新
您应该查看Script Execution Order
.在这里,您可以确保按特定顺序调用类的启动/唤醒/更新功能.它应该列在项目设置下.
You should look into Script Execution Order
. Here you can make sure that the start/ awake/ update functions of classes are called in a certain order. It should be listed under project settings.
初始化场景时,将在所有唤醒/启动功能完成后调用更新(除非将它们定义为协程,但这可能不是您的问题).
When initializing a scene, update will be called after all awake/ start functions have finished (unless they are defined as Coroutines, but this is probably not your issue).
这篇关于Unity对象初始化同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!