유니티/공통

유니티 - Extension(확장 메서드)에 대해 알아보자

근본넘치는개발자 2024. 11. 25. 23:07

오늘은 Unity의 Extension(확장메서드)에 대해 알아보고자 합니다.

 

팀 프로젝트를 진행하면서 스치듯 들은 내용이 생각이 나서

언제, 어떻게 사용하는 건지 한번 찾아서 정리해 봤습니다.

 

확장 메서드( Extension Methods )?

Unity의 기존 클래스를 수정하지 않고 새로운 기능을 추가할 수 있는 프로그래밍 기법

 

원본 소스 코드 접근이 불가능한 클래스(예: Transform)에 기능 확장 시 유용하다.

 

 

사용법

static 클래스에 정의하며 this 키워드로 구현

 

예시 코드

 

using UnityEngine;

public static class TransformExtensions 
{
    // Transform 초기화 확장 메서드
    public static void ResetTransformation(this Transform transform)
    {
        transform.position = Vector3.zero;
        transform.localRotation = Quaternion.identity;
        transform.localScale = Vector3.one;
    }

    // 특정 위치로 부드럽게 이동하는 확장 메서드
    public static void SmoothMoveTo(this Transform transform, Vector3 targetPosition, float speed)
    {
        transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * speed);
    }

    // 자식 오브젝트를 모두 제거하는 확장 메서드
    public static void DestroyChildren(this Transform transform)
    {
        foreach (Transform child in transform)
        {
            Object.Destroy(child.gameObject);
        }
    }
}

public static class GameObjectExtensions
{
    // 컴포넌트 존재 여부 확인 후 가져 오는 확장 메서드
    public static T GetOrAddComponent<T>(this GameObject gameObject) where T : Component
    {
        T component = gameObject.GetComponent<T>();
        if (component == null)
        {
            component = gameObject.AddComponent<T>();
        }
        return component;
    }

    // 레이어 설정 확장 메서드
    public static void SetLayerRecursively(this GameObject gameObject, int layer)
    {
        gameObject.layer = layer;
        foreach (Transform child in gameObject.transform)
        {
            child.gameObject.SetLayerRecursively(layer);
        }
    }
}


// Transform 확장 메서드 사용
transform.ResetTransformation();
transform.SmoothMoveTo(new Vector3(0, 5, 0), 5f);
transform.DestroyChildren();

// GameObject 확장 메서드 사용
Rigidbody rb = gameObject.GetOrAddComponent<Rigidbody>();
gameObject.SetLayerRecursively(8);

 

 

 

마무리 

 

오늘은 간단하게 확장메서드에 대해 알아보았습니다.

 

기존의 상속으로 확장을 진행하려고 했다면

일일이 코드 수정하면서 꽤 번거로웠을 텐데

간단하게 처리 가능한 방법이 있었다니;; 

 

잘 기억해 두었다가

적절한 상황에 사용해 봐야겠네요.

 

참고한 내용 

 

https://youtu.be/C7mdDB3zY1A?si=jM3JiMo0law6qwKh