오늘 주제는 유니티에서 Extension Method(확장 메소드)를 어떤식으로 활용을 할 수 있을까에 대해서 생각해보고 활용 예시를 작성해본다.
Extension Method의 작성 방법과 설명은 아주 간단하다.
static class에 static Method를 만들어주는데 대신 Parameter를 this 키워드와 함께 추가하고자 하는 클래스나 구조체 타입을 작성해주고 내부 처리를 해주면 외부 클래스, 구조체를 수정하지 않고도 새로운 메서드를 추가할 수 있게 된다.
GameObject에서 Component를 자동으로 추가하기
using UnityEngine;
public static class ExtensionMethods
{
public static T GetOrAddComponent<T>(this GameObject obj) where T : Component
{
if (!obj.TryGetComponent<T>(out T component))
component = obj.gameObject.AddComponent<T>();
return component;
}
}
// 사용 예시
public class Ball : MonoBehaviour
{
private SpriteRenderer spriteRenderer;
private Rigidbody2D rb;
private CircleCollider2D circleCollider;
private void Awake()
{
// 실제 GameOjbect에는 GetOrAddComponent라는 함수가 없지만 ExtensionMethod를 추가하여 사용할 수 있다.
spriteRenderer = gameObject.GetOrAddComponent<SpriteRenderer>();
circleCollider = gameObject.GetOrAddComponent<CircleCollider2D>();
rb = gameObject.GetOrAddComponent<Rigidbody2D>();
}
}
여러가지 예시가 있지만, 가장 유용하게 사용할만 한걸로 예시를 작성해봤다.