1인 개발 게임 (Unity)/UNITY

[UNITY] 컴포넌트란? (오브젝트에 성질/기능 추가하기)

Z46 2024. 8. 7. 10:36

안녕하세요, 인친님들! 오늘은 Unity의 핵심인 GameObject와 컴포넌트 시스템에 대해 자세히 알아보겠습니다. 특히 가장 기본이 되는 Transform 컴포넌트를 중심으로 설명하겠습니다.

GameObject와 컴포넌트 시스템

Unity에서 GameObject는 게임 세계의 모든 객체의 기본이 되는 '빈 상자'와 같습니다. 이 빈 상자에 다양한 '컴포넌트'를 추가하여 원하는 기능을 가진 객체를 만들 수 있습니다.

컴포넌트는 간단히 말해 '오브젝트에 성질/기능을 추가하는 것'입니다. 예를 들어, 물리적인 성질을 추가하고 싶다면 Rigidbody 컴포넌트를, 소리를 내고 싶다면 AudioSource 컴포넌트를 추가하는 식입니다. 이렇게 필요한 컴포넌트들을 조합하여 원하는 기능을 가진 게임 오브젝트를 만드는 방식을 '컴포넌트 시스템'이라고 부릅니다.

이 시스템의 장점은 다음과 같습니다:

  1. 모듈화: 각 기능을 독립적인 컴포넌트로 관리할 수 있어 코드 관리가 쉽습니다.
  2. 재사용성: 만든 컴포넼트를 다른 오브젝트에도 쉽게 적용할 수 있습니다.
  3. 유연성: 필요에 따라 컴포넌트를 추가하거나 제거하여 오브젝트의 기능을 쉽게 변경할 수 있습니다.

이제 주요 컴포넌트들과 그 사용법에 대해 자세히 알아보겠습니다.

주요 컴포넌트 소개

  1. Transform: 모든 GameObject에 기본적으로 포함되는 컴포넌트로, 위치, 회전, 크기를 관리합니다. 'AddCompnent'없이 스크립트에 바로 쓸 수 있습니다.
  2. Rigidbody: 물리적인 움직임을 구현할 때 사용합니다.
    예: myObject.AddComponent<Rigidbody>();
  3. AudioSource: 소리를 재생할 때 사용합니다.
    예: myObject.AddComponent<AudioSource>();
  4. 스크립트 컴포넌트: 사용자 정의 동작을 구현할 때 사용합니다. 즉 저희의 입맛대로 스크립트를 만든 뒤에, 그걸 추가할 수 있다는 거죠!
    예: myObject.AddComponent<MyCustomScript>();

GetComponent 메서드

GameObject에 추가된 컴포넌트를 사용하려면 GetComponent 메서드를 사용합니다.

Transform을 제외한 다른 컴포넌트들은 이 메서드를 통해 접근해야 합니다.

// AudioSource 컴포넌트 가져오기
AudioSource audioSource = gameObject.GetComponent<AudioSource>();
if (audioSource != null)
{
    audioSource.Play();
}

// 사용자 정의 스크립트 가져오기
CarController carController = gameObject.GetComponent<CarController>();
if (carController != null)
{
    carController.Run();
}

Transform 컴포넌트 심층 탐구

Transform 컴포넌트는 오브젝트의 위치, 회전, 크기를 관리하는 핵심 컴포넌트입니다. 다른 컴포넌트와 달리 모든 GameObject에 기본적으로 포함되어 있어, getcompnent 나 addcomponet와 같은 메소드없이 transform이라는 이름으로 직접 접근할 수 있습니다.

1. 오브젝트 위치 확인, transform.Position & transform.localPosition

// 현재 오브젝트의 월드 좌표 위치
Vector3 worldPosition = transform.position;
Debug.Log("월드 위치: " + worldPosition);

// 부모 오브젝트가 있다면, 상대적 위치
Vector3 localPosition = transform.localPosition;
Debug.Log("로컬 위치: " + localPosition);

2. 오브젝트 이동 transform.Translate(방향 * 속도);

// 직접 위치 설정
transform.position = new Vector3(1f, 2f, 3f);

// 상대적 이동
transform.Translate(Vector3.forward * Time.deltaTime);

// 부드러운 이동 (Lerp 사용)
Vector3 targetPosition = new Vector3(5f, 0f, 0f);
transform.position = Vector3.Lerp(transform.position, targetPosition, 0.01f);

3. 오브젝트 회전 transform.rotation

// 직접 회전 설정
transform.rotation = Quaternion.Euler(0f, 90f, 0f);

// 상대적 회전
transform.Rotate(Vector3.up * Time.deltaTime);

// 특정 방향 바라보기
Vector3 targetDirection = new Vector3(1f, 0f, 1f);
transform.rotation = Quaternion.LookRotation(targetDirection);

4. 오브젝트 크기 조절 transform.localSacle

// 직접 크기 설정
transform.localScale = new Vector3(2f, 2f, 2f);

// 점진적 크기 변경
transform.localScale += new Vector3(0.01f, 0.01f, 0.01f);

컴포넌트 관련 주요 함수들

Unity에서 컴포넌트를 다룰 때 사용하는 주요 함수들을 알아봅시다. 이 함수들을 잘 활용하면 게임 오브젝트의 기능을 효과적으로 관리할 수 있습니다.

  1. GetComponent()
    이미 추가된 컴포넌트를 가져올 때 사용합니다.
    Rigidbody rb = GetComponent<Rigidbody>();
  2. AddComponent()
    새로운 컴포넌트를 게임 오브젝트에 추가할 때 사용합니다.
    Rigidbody rb = gameObject.AddComponent<Rigidbody>();
  3. GetComponents()
    특정 타입의 모든 컴포넌트를 배열로 가져올 때 사용합니다.
    Collider[] colliders = GetComponents<Collider>();
  4. GetComponentInChildren()
    자식 오브젝트들을 포함하여 특정 타입의 컴포넌트를 찾을 때 사용합니다.
    Light childLight = GetComponentInChildren<Light>();
  5. GetComponentInParent()
    부모 오브젝트에서 특정 타입의 컴포넌트를 찾을 때 사용합니다.
    Rigidbody parentRb = GetComponentInParent<Rigidbody>();
  6. TryGetComponent(out T component)
    컴포넌트를 안전하게 가져오려고 할 때 사용합니다. 컴포넌트가 없어도 에러가 발생하지 않습니다.
    if (TryGetComponent<AudioSource>(out AudioSource audioSource)) { audioSource.Play(); }
  7. GetComponent(Type type)
    런타임에 타입을 지정하여 컴포넌트를 가져올 때 사용합니다.
    Component component = GetComponent(typeof(Rigidbody));
  8. Destroy(Component component)
    특정 컴포넌트를 제거할 때 사용합니다.
    Destroy(GetComponent<Rigidbody>());

이 함수들을 적절히 활용하면 게임 오브젝트의 컴포넌트를 효과적으로 관리할 수 있습니다. 특히 GetComponent() 함수는 매우 자주 사용되므로 잘 기억해두세요!
필요한 컴포넌트를 가져와 조작하는 것이 Unity 개발의 기본입니다.

 

실전 예제: 간단한 플레이어 컨트롤러

이제 이 모든 것을 종합하여 간단한 플레이어 컨트롤러를 만들어 봅시다:

using UnityEngine;

public class SimplePlayerController : MonoBehaviour
{
    public float moveSpeed = 5f;
    public float rotateSpeed = 60f;

    private Rigidbody rb;
    private AudioSource audioSource;

    void Start()
    {
        // Rigidbody와 AudioSource 컴포넌트 가져오기
        rb = GetComponent<Rigidbody>();
        audioSource = GetComponent<AudioSource>();
    }

    void Update()
    {
        // 이동
        float vertical = Input.GetAxis("Vertical");
        transform.Translate(Vector3.forward * vertical * moveSpeed * Time.deltaTime);

        // 회전
        float horizontal = Input.GetAxis("Horizontal");
        transform.Rotate(Vector3.up, horizontal * rotateSpeed * Time.deltaTime);

        // 점프
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Jump();
        }

        // 위치 로그 출력
        Debug.Log("플레이어 위치: " + transform.position);
    }

    void Jump()
    {
        // 위쪽으로 힘을 가해 점프
        rb.AddForce(Vector3.up * 5, ForceMode.Impulse);

        // 점프 소리 재생
        audioSource.Play();
    }
}

이 스크립트는 Transform을 사용한 이동과 회전, Rigidbody를 사용한 점프, 그리고 AudioSource를 사용한 효과음 재생을 모두 포함하고 있습니다.

#유니티 #게임개발 #GameObject #컴포넌트시스템 #Transform #GetComponent #유니티팁