MonoBehaviour

DINO·2023년 12월 9일
0

unity

목록 보기
1/2

MonoBehaviour

: Unity script가 기본적으로 상속 받는 base class.

MonoBehaviour | Unity Manual

MonoBehaviour | Scripting APIl

  • script를 project 창에 생성 시 script는 자동적으로 Monobehaviour를 상속 받는다.
  • MonoBehaviour class는 Start나 Update와 같은 이벤트 함수를 쓸 수 있는 framework를 제공한다. (Start, Update, FixedUpdate etc.)
  • MonoBehaviour를 상속받은 script에 field를 public으로 선언하거나 private으로 선언한 field를 [SerializeField]를 이용하면 inspector 창에서 편집이 가능하다.

  • Coroutine, event message 포함.

MonoBehaviour Life Cycle

Order of execution for event functions | Unity Manual

Initialization

  • Awake
  • OnEnable
  • (Reset : Editor)
  • Start

Physics

  • FixedUpdate

  • Inputevents

Game Logic

  • Update
  • LateUpdate

  • Rendering
  • End of frame
  • Pausing

Decommissioning

  • OnDisable
  • OnDestroy

위는 약식으로 표현한 순서이므로 자세한건 Manual 참고 必

Test 1

실행 순서를 알아보기 위해 다음과 같이 script를 구성하였다.

using UnityEngine;

public class UnityEventTest : MonoBehaviour
{
    private void Awake() => Debug.Log($"{name} : {nameof(Awake)}");
    private void OnEnable() => Debug.Log($"{name} : {nameof(OnEnable)}");
    private void Start() => Debug.Log($"{name} : {nameof(Start)}");

    private void FixedUpdate() => Debug.Log($"{name} : {nameof(FixedUpdate)}");

    void Update()
    {
        Debug.Log($"Current Frame : {Time.frameCount}");
        Debug.Log($"{name} : {nameof(Update)}");
    }

    private void LateUpdate() => Debug.Log($"{name} : {nameof(LateUpdate)}");
    private void OnDisable()
    {
        Debug.Log($"{name} : {nameof(OnDisable)}");
    }

    private void OnDestroy()
    {
        Debug.Log($"{name} : {nameof(OnDestroy)}");
    }
}

Frame 1

Frame 2

Frame 3

Frame 4

  • Frame 1: Awake -> OnEnable -> Start -> FixedUpdate -> Update -> LateUpdate 순서로 실행된다.
  • Frame 2 부터는 FixedUpdate -> Update -> LateUpdate 순으로 실행된다.
  • Component를 비활성화 시키면 OnDisable이 실행된다.

  • 해당 Component를 다시 활성화 시키면 OnEnable부터 LateUpdate가 실행된다. (OnDisable과 OnEnable은 GameObject를 활성화 / 비활성화 시켜도 동일하다.) 이 작용은 이미 Awake가 실행되었던 playmode에서 이어서 하고 있었으므로 OnEnable 부터 시작하는 것이다.

  • OnDestroy의 경우 : Component를 제거 했을 때, (해당 script가 붙어있는)GameObject를 제거했을 때, Scene 전환이 되어 모든 GameObject 파괴되었을 때, Unity playmode를 빠져나갔을 때.

Test2

Component를 여러 개 삽입 후 각 이벤트가 어떻게 동작하는지 알아보았다. test code는 다음과 같다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UnityEventTest : MonoBehaviour
{
    public int Id;

    private void Awake() => Debug.Log($"{name} {Id} : {nameof(Awake)}");
    private void OnEnable() => Debug.Log($"{name} {Id} : {nameof(OnEnable)}");
    private void Start() => Debug.Log($"{name} {Id} : {nameof(Start)}");

    private void FixedUpdate() => Debug.Log($"{name} {Id}: {nameof(FixedUpdate)}");

    void Update()
    {
        Debug.Log($"Current Frame : {Time.frameCount}");
        Debug.Log($"{name} {Id} : {nameof(Update)}");
    }

    private void LateUpdate() => Debug.Log($"{name} {Id} : {nameof(LateUpdate)}");
    private void OnDisable()
    {
        Debug.Log($"{name} {Id} : {nameof(OnDisable)}");
    }

    private void OnDestroy()
    {
        Debug.Log($"{name} {Id} : {nameof(OnDestroy)}");
    }
}

  • Awake, OnEnable : Awake, OnEnable이 순차적으로 진행된 다음 다른 Component가 실행되는 것을 확인할 수가 있다.

  • Start 또한 Initialization 단계에서 실행되는 event 함수이지만 Awake와 OnEnable과 함께 순차적으로 call 되지는 않았다.

  • Start 이후에도 각 component 단위로 이벤트 함수가 호출되는 것을 알 수가 있다.

  • OnDisable, OnDestroy 또한 연달아 불리는 것이 아니라 OnDisable이 끝나고 OnDestroy가 불려지는 것을 알 수가 있다.

  • Component 간의 호출 순서는 정해져 있지 않다. 이는 GameObject도 마찬가지이다. 순서를 명시하고 싶으면 스크립트로 동적으로 할당 하는 것이 일반적이다.

MonoBehaviour Life Cycle (Script lifecycle) Summary

  1. Awake() -> OnEnable() -> Start() -> FixedUpdate() -> Update() -> LateUpdate() -> OnDisable() -> OnDestroy() 순으로 동작한다. (OnDisable과 OnDestroy가 모두 동작한다는 전제 하에)
  2. Awake() vs. OnEnable() vs. Start()
    Awake()와 OnEnable()은 순차적으로 함께 호출된다. 즉, Awake() -> OnEnable() 이 순서로 호출 후, 다음 component 넘어간다. 그러나 Start의 경우에는 모든 component의 동작이 끝나야 실행된다.
  3. Component 및 GameObject 비활성화
    - Component 비활성화 시 -> Awake()만 호출됨.
    - GameObject 비활성화 시 -> 호출 되지 않는다.
  4. Update() vs. Fixed Update() vs. LateUpdate()
    - Update(): 매 Frame 마다 호출되는 함수. CPU의 성능에 따라 호출되는 간격이 다르다.
    - Fixed Update() : Fixed Time Step에 따라 일정한 간격(0.02s / 약 50fps)으로 호출되는 함수. Update()가 CPU의 성능에 따라 호출 간격이 다름에 따라 일어나는 문제를 보완해준다. 주로 물리적인 연산에서 사용된다.
    - LateUpdate(): FixedUpdate() -> Update()의 연산과 모든 내부 애니메이션 update가 끝난 후 호출되는 함수. 자주 쓰는 예시로 player를 비추는 3인칭 카메라를 구현할 때 사용이 된다.
  5. OnDisable(), OnDestory()
    - OnDisable()은 component 및 GameObject()가 비활성화 될 때 호출된다.
    - OnDestroy()는 다음과 같은 상황에서 호출된다.
    - Component를 제거했을 때
    - GameObject를 제거했을 때
    - Scene이 전환되어 모든 GameObject가 파괴되었을 때
    - Unity Playmode를 빠져나갔을 때
    - 당연한 이야기이지만 OnDestroy의 상황에서 먼저 호출 되지 않은 이상, OnDisable()이 함께 호출된다.

Event Function | Unity Manual

profile
NEWB!

0개의 댓글