默认情况下已启用场景重新加载。这意味着,进入运行模式时,Unity 会销毁所有现有的场景游戏对象并从磁盘重新加载场景。Unity 执行此操作所需的时间随场景复杂性而增加,这意味着随着项目日益复杂,在按下 Play 按钮到场景完全载入编辑器之间必须等待更长的时间。
禁用场景重新加载后,该过程将花费更少的时间。这使您可以更快地迭代项目的开发。Unity 不会从磁盘重新加载场景,而是仅重置场景的已修改内容。这样可避免卸载和重新加载场景所造成的时间和性能影响。Unity 仍然会调用相同的初始化函数(例如 OnEnable
、OnDisable
和 OnDestroy
),就像刚加载时一样。
To disable Scene Reloading:
For more information, see How to configure Play Mode
在禁用场景重新加载时,在编辑器中启动应用程序所花费的时间不再表示在所构建的版本中启动的时间。因此,如果想对项目启动期间发生的情况进行准确调试或性能分析,应当启用场景重新加载以便更准确地表示所构建的应用程序版本中的真实加载时间和过程。
禁用场景重新加载应该对项目产生最小的副作用。然而,因为场景重新加载与域重新加载紧密相连,所以有一些重要的区别:
未序列化到构建版本中的 ScriptableObject 和 MonoBehaviour 字段([NonSerialized]`、private 或 internal)保持它们的值。这是因为 Unity 不会重新创建现有对象,也不会调用构造函数。此外,在域重新加载期间,Unity 将数组/List 类型的 null private 和 internal 字段转换为空数组/List 对象,对于运行时(非编辑器)脚本,则保持非 null。
使用 ExecuteInEditMode
或 ExecuteAlways
脚本的脚本不会收到 OnDestroy
或 Awake
调用。Unity 不调用 Awake,仅当使用 Awake/OnEnable 方法(检查 EditorApplication.isPlaying
属性)更改运行模式时 EditorApplication.isPlaying
已为真的情况下,才会调用 OnEnable 方法。运行时(非编辑器)脚本的非序列化字段应该不是问题,因为它们在编辑模式下不是活动的,但是标有 ExecuteInEditMode
或 ExecuteAlways
的脚本可能会改变自己或影响其他运行时脚本的字段。要解决此问题,请自行在 OnEnable 回调中初始化所有受影响的字段。
Did you find this page useful? Please give it a rating:
Thanks for rating this page!
What kind of problem would you like to report?
Thanks for letting us know! This page has been marked for review based on your feedback.
If you have time, you can provide more information to help us fix the problem faster.
Provide more information
You've told us this page needs code samples. If you'd like to help us further, you could provide a code sample, or tell us about what kind of code sample you'd like to see:
You've told us there are code samples on this page which don't work. If you know how to fix it, or have something better we could use instead, please let us know:
You've told us there is information missing from this page. Please tell us more about what's missing:
You've told us there is incorrect information on this page. If you know what we should change to make it correct, please tell us:
You've told us this page has unclear or confusing information. Please tell us more about what you found unclear or confusing, or let us know how we could make it clearer:
You've told us there is a spelling or grammar error on this page. Please tell us what's wrong:
You've told us this page has a problem. Please tell us more about what's wrong:
Thank you for helping to make the Unity documentation better!
Your feedback has been submitted as a ticket for our documentation team to review.
We are not able to reply to every ticket submitted.