Skip to content

Instantly share code, notes, and snippets.

@ngcbbs
Created January 31, 2025 01:22
Show Gist options
  • Select an option

  • Save ngcbbs/111ea1fc35c70b89f8a6fbef21daa64d to your computer and use it in GitHub Desktop.

Select an option

Save ngcbbs/111ea1fc35c70b89f8a6fbef21daa64d to your computer and use it in GitHub Desktop.
MonoBehaviour 실행 순서 정리

📌 MonoBehaviour 실행 순서 정리

✅ 객체 생성 시 (Awake → OnEnable → Start)

  1. Awake()

    • 가장 먼저 실행됨
    • GameObject가 활성화(active = true) 상태가 아니어도 실행됨
    • DontDestroyOnLoad() 설정 가능
  2. OnEnable()

    • GameObject 또는 Component가 활성화될 때 실행됨
    • Awake() 이후에 실행됨
  3. Start()

    • Awake()OnEnable() 이후 한 번 실행됨
    • Update()가 실행되기 전에 실행됨
    • 다른 스크립트에서 GameObject를 참조하려면 Start()에서 초기화하는 것이 좋음

✅ 객체 비활성화 시 (OnDisable)

  1. OnDisable()
    • GameObject 또는 Component가 비활성화될 때 실행됨
    • OnEnable()의 반대 개념

✅ 프레임 업데이트 관련 (Update → FixedUpdate → LateUpdate)

  1. FixedUpdate()

    • 물리 연산과 관련된 업데이트 (고정된 시간 간격으로 실행됨)
    • Time.fixedDeltaTime 주기로 실행됨
    • Rigidbody 관련 로직은 여기에 작성하는 것이 좋음
  2. Update()

    • 매 프레임마다 실행됨
    • 게임 로직, 입력 처리 등을 실행
  3. LateUpdate()

    • Update() 실행 후 호출됨
    • 카메라 추적 등 다른 객체의 움직임을 반영한 후 실행할 로직을 넣기 좋음

✅ 오브젝트 파괴 시 (OnDestroy)

  1. OnDestroy()
    • Destroy(gameObject)가 호출되면 실행됨
    • 씬이 변경될 때도 실행됨
    • 할당된 리소스를 정리하는 데 사용됨

✅ 씬 변경 시 (OnApplicationQuit → OnDestroy)

  1. OnApplicationQuit()
    • 애플리케이션이 종료될 때 실행됨
    • 에디터에서 Play 버튼을 해제할 때도 호출됨

🎯 실행 순서 정리 (표)

실행 시점 실행 함수 설명
객체 생성 Awake() 가장 먼저 실행됨 (비활성화 상태여도 실행)
OnEnable() GameObject 또는 Component가 활성화될 때 실행
Start() OnEnable() 후 한 번 실행됨
매 프레임 실행 FixedUpdate() 고정된 시간 간격으로 실행 (물리 연산)
Update() 매 프레임 실행 (게임 로직)
LateUpdate() Update() 후 실행 (카메라 추적 등)
객체 비활성화 OnDisable() GameObject 또는 Component가 비활성화될 때 실행
객체 삭제 OnDestroy() Destroy()가 호출되거나 씬이 변경될 때 실행
애플리케이션 종료 OnApplicationQuit() 애플리케이션 종료 시 실행

🔥 실제 예제 코드

using UnityEngine;

public class MonoBehaviourExample : MonoBehaviour
{
    void Awake()
    {
        Debug.Log("Awake 실행됨");
    }

    void OnEnable()
    {
        Debug.Log("OnEnable 실행됨");
    }

    void Start()
    {
        Debug.Log("Start 실행됨");
    }

    void FixedUpdate()
    {
        Debug.Log("FixedUpdate 실행됨");
    }

    void Update()
    {
        Debug.Log("Update 실행됨");
    }

    void LateUpdate()
    {
        Debug.Log("LateUpdate 실행됨");
    }

    void OnDisable()
    {
        Debug.Log("OnDisable 실행됨");
    }

    void OnDestroy()
    {
        Debug.Log("OnDestroy 실행됨");
    }

    void OnApplicationQuit()
    {
        Debug.Log("OnApplicationQuit 실행됨");
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment