07/14 Unity C# 기초 스크립팅과 컴포넌트

심지태
∙∙조회 3
07/14 Unity C# 기초 스크립팅과 컴포넌트

Awake()와 Start() 차이

구분AwakeStart
호출 시점오브젝트 초기화 시첫 프레임 실행 직전 (Update 실행 직전)
호출 순서Start보다 먼저Awake 이후
주요 용도내부 초기화, 참조 설정다른 오브젝트를 이용한 초기화
호출 횟수한 번한 번
스크립트 비활성화호출 가능활성화될 때 호출

Awake → OnEnable → Start → Update

Awake와 Start의 차이

Awake - 게임 오브젝트가 생성될 때, 즉시 호출됨.

Start - 생성된 다른 오브젝트의 컴포넌트에 참조하기 위해서 생성 이후에 실행됨

 

Unity OnEnable / OnDisable

메서드호출 시점주요 용도
OnEnable()오브젝트와 컴포넌트가 활성화될 때이벤트 등록, 기능 시작, 상태 초기화
OnDisable()오브젝트 또는 컴포넌트가 비활성화될 때이벤트 해제, 기능 중지, 자원 정리

Update / LateUpdate / FixedUpdate

-> 업데이트 호출 순서 : FixedUpdate/Update/LateUpdate

메서드호출 시점주요 용도
Update()매 프레임마다 호출입력 처리, 일반 게임 로직
LateUpdate()Update() 실행 후 호출카메라 추적, 최종 위치 보정
FixedUpdate()일정한 시간 간격으로 호출물리 연산, Rigidbody 제어

OnMouseDown(), OnMouseDrag(), OnMouseEnter(), OnMouseExit(), OnMouseOver(), OnMouseUp()

메서드호출 시점주요 용도
OnMouseDown()오브젝트를 클릭했을 때선택, 클릭 동작 시작
OnMouseDrag()클릭한 상태로 마우스를 움직일 때오브젝트 드래그
OnMouseEnter()커서가 오브젝트 영역에 들어왔을 때강조 효과, 색상 변경
OnMouseExit()커서가 오브젝트 영역에서 나갔을 때강조 효과 해제, 색상 복구
OnMouseOver()커서가 오브젝트 위에 있는 동안마우스 오버 상태 처리
OnMouseUp()마우스 버튼을 뗐을 때클릭·드래그 동작 종료

유니티 생명 주기 순서

Awake() -> OnEnabled() -> Start() -> FixedUpdate() -> Update() -> LateUpdate() -> OnDisable()

 

Unity 인스펙터 어트리뷰트(Inspector Attributes)

Attribute사용 대상역할예시
[SerializeField]private 필드비공개 필드를 Unity가 저장하고 Inspector에 표시[SerializeField] private int health;
[HideInInspector]직렬화 필드값은 저장하지만 Inspector에서는 숨김[HideInInspector] public int id;
[Header("제목")]필드해당 필드 위에 굵은 구분 제목 표시[Header("이동 설정")]
[Tooltip("설명")]필드마우스를 올렸을 때 설명 표시[Tooltip("초당 이동 거리")]
[Range(min, max)]숫자 필드숫자를 슬라이더로 표시[Range(0f, 10f)]
[Min(min)]숫자 필드Inspector에서 입력할 수 있는 최솟값 지정[Min(0f)]
[Space]필드필드 위에 세로 여백 추가[Space(10)]
[TextArea]string 필드여러 줄 텍스트 입력창으로 표시[TextArea(3, 10)]
[Multiline]string 필드지정한 줄 수의 여러 줄 입력창으로 표시[Multiline(5)]
[FormerlySerializedAs]이름을 바꾼 필드필드명을 변경해도 기존 Scene/Prefab 값을 유지[FormerlySerializedAs("oldHealth")]

Unity GetComponent 계열 정리

메서드검색 범위결과비활성 오브젝트예시
GetComponent<T>()현재 GameObject첫 번째 1개현재 오브젝트 대상GetComponent<Rigidbody>()
TryGetComponent<T>()현재 GameObject성공 여부 + 1개현재 오브젝트 대상TryGetComponent(out Rigidbody rb)
GetComponents<T>()현재 GameObject조건에 맞는 전체현재 오브젝트 대상GetComponents<Collider>()
GetComponentInChildren<T>()현재 + 모든 자식첫 번째 1개기본적으로 제외GetComponentInChildren<Animator>()
GetComponentsInChildren<T>()현재 + 모든 자식조건에 맞는 전체기본적으로 제외GetComponentsInChildren<Renderer>()
GetComponentInParent<T>()현재 + 모든 부모첫 번째 1개기본적으로 제외GetComponentInParent<Player>()
GetComponentsInParent<T>()현재 + 모든 부모조건에 맞는 전체기본적으로 제외GetComponentsInParent<Canvas>()

컴포넌트 추가·조회·제거 관련 메서드

메서드/속성역할대상예시
AddComponent<T>()컴포넌트를 추가하고 참조 반환GameObjectgameObject.AddComponent<Rigidbody>()
AddComponent(Type)실행 중 결정된 타입의 컴포넌트 추가GameObjectgameObject.AddComponent(componentType)
GetComponent<T>()컴포넌트 하나 조회현재 GameObjectGetComponent<Rigidbody>()
TryGetComponent<T>()존재 여부를 확인하면서 조회현재 GameObjectTryGetComponent(out Rigidbody rb)
GetComponents<T>()같은 타입의 컴포넌트를 모두 조회현재 GameObjectGetComponents<Collider>()
Destroy(component)특정 컴포넌트 제거ComponentDestroy(rb)
Destroy(gameObject)GameObject 전체 제거GameObjectDestroy(gameObject)
component.enabled컴포넌트를 제거하지 않고 활성화/비활성화Behaviour 계열collider.enabled = false
gameObject.SetActive()GameObject 전체 활성화/비활성화GameObjectgameObject.SetActive(false)
DestroyImmediate()즉시 제거주로 에디터 코드DestroyImmediate(component)

Time.deltaTime