flrto

GetComponent<>(); 의 제네릭(Generic) 기법 본문

Unity/TIL

GetComponent<>(); 의 제네릭(Generic) 기법

갈릭새우칩 2019. 5. 17. 17:36
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public class PlayerController : MonoBehaviour
{
    private Rigidbody playerRigidbody;   // 이동에 사용할 리지드바디 컴포넌트
    public float speed = 16f;            //이동 속력
    
    void Start()
    {
        playerRigidbody = GetComponent<Rigidbody>(); //리지드바디 컴포넌트를 유니티 에디터에서 직접 드래그&드랍
    }                                                 //하지 않고 코드가 할당하게 함
 
    void Update()
    {
 
    }
    public void Die()
    {
        //자신의 게임 오브젝트를 비활성화
        gameObject.SetActive(false);
    }
}
 
 

void Start()

{

    playerRigidybody = GetComponent<Rigidbody>();

}

 

다음의 GetComponent()메서드에서 사용한 꺾쇠 <> 는 제네릭(Generic)기법이다.

 

※ 참고 Getcomponent()는 한번만 호출하여 객체를 캐싱해두고 사용한다.

 

제네릭은 메서드나 클래스가 여러 타입에 호환 되게 한다. 꺾쇠안에 원하는 타입을 명시하면 클래스나 메서드가 해당 

타입에 맞춰 동작한다.

 

제네릭을 사용하지 않으면 처리를 위한 여러 타입의 메서드나 클래스를 일일히 만들어야 한다.

 

예를 들자면

 

· GetComponentRigibody()

· GetComponentTransform()

· GetComponentRenderer()

· ....

 

위와 같은 문제를 해결하기 위해 GetComponent()는 제네릭을 사용할 수 있도록 구현되어 있으며

 

제네릭 덕분에 하나의 GetComponent() 메서드로 모든 타입의 컴포넌트에 대응할 수 있다.

Comments