1. Common life cycle methods in Unity
1Awake(),2OnEnable(), 3Start(), 4FixedUpdate(), 5Update(), 6LateUpdate(), 7OnGUI(), 8OnDisable(), 9OnDestroy().
2. Usual execution sequence
A special method Reset()
Reset
Methods are called in the editor and are only executed when:
-
Script component is added to GameObject: When you add a script component to a GameObject, if the script contains the
Reset
method, This method will be called immediately after the component is added. -
The public fields or properties of the script are modified in the editor: If the public fields or properties of the script are modified in the Inspector, the
Reset
method will Called when you stop editor playback or reload the scene. -
Reset component: In the Inspector, right-click the title bar of the script component and select the "Reset" option to manually trigger the
Reset
method .
The purpose of this design is to ensure that modifications to script properties in the editor can be reflected in the scene in a timely manner, and at the same time provide an opportunity to ensure that the property values in the editor are consistent with the initial state of the script. The Reset
method is useful for debugging, initializing, and synchronizing property state in the editor. At runtime (in the actual game after building), the Reset
method is not called.
1.Awake():
First call the Awake method. At this stage, the object is instantiated, but not yet activated. He is called before the OnEnable and Start methods.
2.OnEnable():
If the object is enabled, then OnEnable is called. This is the first method when the object becomes active.
3.Start():
Method calling timing: Called when the object is updated for the first time. Used for initialization, but called after Awake.
4.FixedUpdate() and Update():
After the Start method is executed, the FixedUpdate method is called at a fixed time interval, and then the Update method is called at each frame.
5.LateUpdate():
After the Update method is executed, the LateUpdate method is called. Usually used for operations such as camera following, ensuring that it is executed after all Update methods have been executed.
6.OnGUI():
After the LateUpdate method is executed, the OnGUI method is called. Used for rendering GUI elements.
7.OnDisable():
If the object is disabled, the OnDisable method is called. Perform some cleanup work when the object is disabled.
8.OnDestroy():
If the object is destroyed, the OnDestroy method is finally called. Perform final cleanup when the object is destroyed.
3. Some usage suggestions
1. When using wake and start:
1. Called only once in the life cycle
2.awake is called before start, and the start method of a certain game object cannot be called until the wake methods of all game objects have been called. Therefore, if there is a requirement in the start method that needs to be obtained in advance before it can be run, it must be written in awake. To avoid errors.
3. Avoid performing too time-consuming operations in Awake
or Start
to avoid affecting game startup performance. These two methods should be used for lightweight initialization work.
4. The constructor of the script usually precedes Awake
and Start,但在unity中一般不直接使用构造函数。
2.Update
, FixedUpdate
sum LateUpdate的区别
- Update:
- Calling frequency: will be called every frame.
- Purpose: is used to handle code related to game logic and user input.
- Recommended usage: Handle input, game logic, player control, etc.
- FixedUpdate:
- Call frequency: Called at a fixed time interval, usually 50 times per second by default.
- Purpose: is used to process physics calculations and updates to ensure consistent results of physics simulations on different platforms.
- Recommended usage: Handle rigid body motion, physical collision, etc.
- LateUpdate:
- Call frequency: is called after all
Update
andFixedUpdate
methods have been executed. - Purpose: is used to handle camera following logic, ensuring that the position and rotation of all objects are updated before execution.
- Recommended usage: Process camera following, post-processing effects, etc.
- Call frequency: is called after all
Recommended to use:
- Try to put user input and game logic in
Update
because it is called every frame and is suitable for processing operations with high real-time nature. - Place physics-related calculations in
FixedUpdate
to ensure that physics updates are performed at fixed intervals, making the physics simulation more accurate. - Use
LateUpdate
to handle the camera following logic, ensuring that the position and rotation of all objects are updated before executing to avoid jitter or instability in camera following.
3.The difference between onEnable and ondisable
OnEnable
:- Call time: Called when the object becomes active (enabled), whether when the scene starts running or when the script is instantiated.
- Usage: is usually used for operations such as initialization work, resource loading, subscribing to events or starting coroutines to ensure execution when the object is activated.
- Note: Do not perform time-consuming operations in
OnEnable
as it may affect the game's startup performance.
OnDisable
:- Calling timing: Called when the object becomes inactive (disabled), for example, the object is disabled or destroyed.
- Usage: is usually used for cleanup work, unsubscribing from events, stopping coroutines, etc. to ensure execution when the object is disabled or destroyed.
- Note: Do not perform operations in
OnDisable
that require the object to be active.
Recommended to use:
- Carry out resource loading, initialization, event subscription and other operations in
OnEnable
to ensure that they are executed when the object is activated. - Carry out cleanup work, unsubscribe events, stop coroutines, etc. in
OnDisable
to ensure execution when the object is disabled or destroyed. - Avoid performing too many time-consuming operations in
OnEnable
andOnDisable
that may impact game performance.
Combined use of OnEnable
and OnDisable
methods can implement some necessary initialization and cleanup logic in the life cycle of the object to ensure that the object is activated and disabled able to perform specific operations.
4. Questions that may be asked in the interview
1. What is the execution order of life cycle methods?
Awake
, OnEnable
, Start
, FixedUpdate
, Update
, LateUpdate
, OnGUI
, OnDisable
, OnDestroy
.
2. Why is Awake
sometimes used instead of Start
?
Awake
is called when the object is instantiated and is usually used for initialization, while Start
is executed after Awake
and is suitable for one-time initialization work. If you need to ensure that the Awake
stage of all scripts is executed, you can use Awake
.
3.LateUpdate
What kind of situations does it apply to?
LateUpdate
Suitable for processing camera following logic, ensuring that the position and rotation of all objects are updated before execution to avoid camera shake or instability.
4. How to handle cleanup when objects are disabled and destroyed?
OnDisable
is used to perform cleanup operations when the object is disabled, and OnDestroy
is used to perform final cleanup when the object is destroyed.
5. Why not perform physical calculations in Update
?
FixedUpdate
It is suitable for handling physics calculations because it is called at fixed intervals, ensuring consistent results of physics simulations on different platforms.
6. How to perform initialization operations in the editor?
Perform initialization operations in the Reset
method to ensure that modifications to script properties in the editor can be reflected in the scene in a timely manner.
7. In which life cycle methods can coroutines be used?
Coroutines are usually used in Start
or later life cycle methods, and are not recommended for use in Awake
.
8. How often are life cycle methods executed and how to optimize performance?
How often lifecycle methods are executed depends on how often the engine calls them. Avoiding performing too many calculations in these methods can improve performance.
9. How to deal with the problems of singleton mode in Unity life cycle?
Use the Awake
method to ensure that the singleton pattern is initialized when the object is instantiated, and use the OnDestroy
method to handle cleanup when the object is destroyed.
example
public class GameManager : MonoBehaviour
{
// 单例模式实例
private static GameManager instance;
// 获取单例实例的方法
public static GameManager Instance
{
get
{
if (instance == null)
{
// 如果实例不存在,则尝试在场景中找到已有的实例
instance = FindObjectOfType<GameManager>();
// 如果场景中不存在实例,则创建一个新的实例
if (instance == null)
{
GameObject obj = new GameObject("GameManager");
instance = obj.AddComponent<GameManager>();
}
}
return instance;
}
}
// 在 Awake 中确保单例的正确性
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject); // 防止在场景切换时被销毁
}
else
{
Destroy(gameObject); // 如果有重复的实例,销毁新创建的实例
}
}
// 游戏初始化逻辑
private void Start()
{
// 这里可以添加游戏初始化的逻辑
}
// 游戏结束时的清理工作
private void OnDestroy()
{
// 这里可以添加游戏结束时的清理工作
}
}
10.What is the difference between the life cycle methods of MonoBehaviour and non-MonoBehaviour classes?
The life cycle methods of the MonoBehaviour class are called by the engine to manage the life cycle of the object, while non-MonoBehaviour classes do not have these special life cycle methods. In non-MonoBehaviour classes, you need to manually manage object initialization and cleanup.