[Unity]GetComponent 함수

Inhwan98·2023년 3월 28일
0

Unity끄적

목록 보기
6/8

언제사용?

(자신) 게임오브젝트에 추가된 컴포넌트 중에서 원하는 컴포넌트를 참조(추출)할 때 사용한다.

추출할 (컴포넌트)클래스 tr;

tr = GetComponent<추출할 (컴포넌트)클래스>();


ex)
Transform tr;

tr = GetComponent<Transform>();

GetComponent 함수의 다양한 사용문법

tr = GetComponent<Transform>();
tr = GetComponent<“Transform”) as Transform;
tr = (Transform)GetComponent(typeof(Transform));

this.gameObject의 생략

tr = this.gameObject.GetComponent();

  • GetComponent()는 this.gameObject 가 생략되어 있다.
  • 의미 : “이 스크립트가 포함된 게임오브젝트가 가진 여러 컴포넌트 중에서 Transform 컴포넌트를 추출해 tr변수에 저장하라.”

🔑Unity에서 this 키워드

C#에서 this 라는 키워드는 해당 클래스(스크립트)를 의미한다. Unity에선 해당 스크립트가 포함된 게임오브젝트를 의미하기 때문에 this.gameObject 키워드는 생략할 수 있다.


서적 참고 : 절대강좌! 유니티 2021

profile
코딩마스터

0개의 댓글