Unity / C#
Beginner
Unity 2021.3+ / Unity 6
MonoBehaviour 생명주기(Awake · Start · Update · FixedUpdate · LateUpdate) 핵심 정리MonoBehaviour Lifecycle and Execution Order Essentials (Awake, Start, Update, FixedUpdate, LateUpdate)
초기화 순서 꼬임(NullReferenceException) 방지 원칙, 물리 틱과 렌더 프레임 분리 이유, Time.deltaTime과 Time.fixedDeltaTime의 올바른 사용 가이드.Guidelines for preventing initialization order errors (NullReferenceException), separating physics ticks from render frames, and properly using Time.deltaTime and Time.fixedDeltaTime.
#Unity #C# #MonoBehaviour #Lifecycle #Execution Order #Update
핵심 개념유니티 초심자가 겪는
NullReferenceException의 대부분은 Awake와 Start의 초기화 책임 분리 원칙을 지키지 않아서 발생합니다. 또한 물리 연산과 카메라 추적이 각각 FixedUpdate와 LateUpdate에 격리되어야 화면 떨림(Jitter) 없는 안정적인 게임 플레이를 구현할 수 있습니다.Core ConceptMost
NullReferenceException errors encountered by beginners in Unity occur when the separation of initialization responsibilities between Awake and Start is not maintained. In addition, isolating physics calculations in FixedUpdate and camera tracking in LateUpdate is required to avoid camera jitter.1. 3단계 초기화 및 업데이트 루프 매트릭스1. Initialization and Update Loop Matrix
좌우로 밀어서 표 전체 내용을 확인하세요
| 메서드 | 실행 주기 | 주요 목적 및 권장 작업 | 델타 타임 인자 |
|---|---|---|---|
| Awake() | 씬 로드 시 1회 (비활성 컴포넌트도 부모 활성이면 실행) | 컴포넌트 자체 참조 캐싱(GetComponent), 내부 상태 초기화 | - |
| OnEnable() | 오브젝트/컴포넌트 활성화될 때마다 | 이벤트 리스너 등록, 델리게이트 구독 | - |
| Start() | 첫 번째 프레임 업데이트 직전 1회 (컴포넌트 활성 상태 필수) | 타 오브젝트/매니저와의 상호작용(Find, Singleton 데이터 수신) | - |
| FixedUpdate() | 고정 주기 (기본 0.02초, 50Hz) | 물리 엔진 연산(Rigidbody, 힘 가하기, 충돌 감지) | Time.fixedDeltaTime |
| Update() | 매 렌더링 프레임마다 (가변 주기) | 유저 입력 감지(Input), 애니메이션 파라미터 제어, 비물리 연산 | Time.deltaTime |
| LateUpdate() | 모든 Update() 종료 후 실행 | 카메라 위치 추적, 애니메이션 본 트랜스폼 오버라이드 | Time.deltaTime |
| OnDisable() | 오브젝트 비활성화 또는 씬 전환 시 | 이벤트 구독 해제, 진행 중인 트윈/코루틴 정리 | - |
Swipe horizontally to view the full table
| Method | Execution Frequency | Primary Purpose & Recommended Tasks | Delta Time Multiplier |
|---|---|---|---|
| Awake() | Once on scene load (runs on disabled components if GameObject is active) | Cache self-component references (GetComponent), initialize internal state | - |
| OnEnable() | Every time the GameObject or component becomes enabled | Register event listeners, subscribe delegates | - |
| Start() | Once before the first frame update (requires enabled component) | Interact with other objects or managers (Find, read Singleton data) | - |
| FixedUpdate() | Fixed interval (default 0.02s, 50Hz) | Physics engine calculations (Rigidbody, applying forces, collision checks) | Time.fixedDeltaTime |
| Update() | Every rendered frame (variable interval) | Poll user input (Input), update animator parameters, non-physics logic | Time.deltaTime |
| LateUpdate() | Every frame after all Update() calls finish | Camera follow tracking, procedural bone transform overrides | Time.deltaTime |
| OnDisable() | When disabled or unloaded during scene transitions | Unsubscribe events, stop active tweens or coroutines | - |
2. 흔한 실수와 방지 코드 패턴2. Common Mistakes and Prevention Pattern
using UnityEngine;
public class CameraFollower : MonoBehaviour
{
[SerializeField] private Transform target;
[SerializeField] private Vector3 offset = new Vector3(0f, 2f, -10f);
[SerializeField] private float smoothSpeed = 10f;
// [잘못된 예]: Update()에서 카메라를 추적하면 타겟(FixedUpdate에서 이동)과 프레임이 어긋나 화면 떨림 발생
// [올바른 예]: LateUpdate()에서 추적하여 모든 오브젝트의 이동이 끝난 최종 위치를 캡처
private void LateUpdate()
{
if (target == null) return;
Vector3 desiredPosition = target.position + offset;
transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed * Time.deltaTime);
}
}
using UnityEngine;
public class CameraFollower : MonoBehaviour
{
[SerializeField] private Transform target;
[SerializeField] private Vector3 offset = new Vector3(0f, 2f, -10f);
[SerializeField] private float smoothSpeed = 10f;
// [Incorrect]: Updating camera follow in Update() causes jitter when target moves in FixedUpdate
// [Correct]: Track in LateUpdate() to capture final positions after all movement finishes
private void LateUpdate()
{
if (target == null) return;
Vector3 desiredPosition = target.position + offset;
transform.position = Vector3.Lerp(transform.position, desiredPosition, smoothSpeed * Time.deltaTime);
}
}
3. 프로젝트 스크립트 실행 순서(Execution Order) 커스텀3. Customizing Script Execution Order
[DefaultExecutionOrder(-100)]: 싱글톤 매니저(GameManager,SoundManager등) 클래스 위에 해당 어트리뷰트를 붙이면 일반 스크립트보다 먼저Awake가 실행되어 참조 실패를 방지합니다.- 빈 이벤트 함수 삭제: 스크립트 템플릿에 기본으로 포함된 빈
Update()나FixedUpdate()는 유니티 네이티브-C# 런타임 간의 불필요한 P/Invoke 컨텍스트 스위칭 오버헤드를 유발하므로 쓰지 않는다면 삭제해야 합니다.
[DefaultExecutionOrder(-100)]: Placing this attribute above singleton manager classes (GameManager,SoundManager, etc.) ensures theirAwakeruns before regular scripts, preventing null reference issues.- Remove Empty Event Functions: Empty
Update()orFixedUpdate()methods left from script templates still incur native-to-managed C# invocation overhead on every frame and should be removed if unused.
각 생명주기 메서드의 호출 시점과 역할을 명확히 구분하여 코드를 배치하면 초기화 순서 충돌과 물리·렌더링 프레임 불일치 문제를 예방할 수 있습니다.
Assigning responsibilities according to each lifecycle method's execution phase helps prevent initialization race conditions and frame synchronization issues between physics and rendering.