Performance: MonoBehaviour lifecycle
This affects the frame rendering speed and responsiveness of Unity games by controlling when and how often scripts run during the game loop.
void Start() {
// Precompute data once
precomputedData = ComputeHeavyData();
}
void Update() {
// Use precomputed data without allocations
UseData(precomputedData);
}void Update() {
// Heavy calculations or frequent allocations here
for (int i = 0; i < 1000; i++) {
var temp = new Vector3(i, i, i);
}
}| Pattern | CPU Usage | Frame Drops | Garbage Collection | Verdict |
|---|---|---|---|---|
| Heavy work in Update | High CPU every frame | Frequent frame drops | High GC pressure | [X] Bad |
| Precompute in Start, light Update | Low CPU per frame | Smooth frames | Minimal GC | [OK] Good |
Awake() is called once when the script instance is loaded, before Start().Update() and FixedUpdate() run repeatedly, and OnDestroy() runs when the object is destroyed.Update are usually declared as void Update() without access modifiers.using UnityEngine;
public class TestLifecycle : MonoBehaviour {
void Awake() {
Debug.Log("Awake called");
}
void Start() {
Debug.Log("Start called");
}
void Update() {
Debug.Log("Update called");
enabled = false;
}
}
Assuming the game runs for one frame, what messages appear in the Console?Awake() runs once at load, then Start() runs before first Update, then Update() runs.Update() method disables the script after logging, so it runs once this frame only.using UnityEngine;
public class Example : MonoBehaviour {
void Start() {
Debug.Log("Start called");
}
void Update() {
Debug.Log("Update called");
}
void OnDestroy() {
Debug.Log("Destroying object");
}
void awake() {
Debug.Log("Awake called");
}
}awake() is incorrect; it must be Awake().OnDestroy() returns void, Update() can have Debug.Log, and Start() is instance method, not static.OnDestroy() is called just before the object is destroyed, ideal for cleanup.OnDestroy() to avoid memory leaks or errors.Pass the test and this pattern moves unknown