확장메서드 (Extension Method)
원본 클래스나 소스 코드를 직접 수정하거나 상속받지 않고도, 기존 형식에 새로운 메서드를 추가할 수 있는 기능입니다.
- 작성 조건 (C# 기준)
- 정적 클래스 ==(Static Class)== 내에 정의해야 합니다.
- 메서드 자체도 정적 메서드 ==(Static Method)== 여야 합니다.
- 첫번째 매개변수에
this키워드와 함께 확장하고자 하는 대상 타입을 명시해야 합니다.
- 예시 : LayerMask 검사용
LayerMaskExtensions.cs스크립트
public static class LayerMaskExtensions
{
public static bool Contains(this LayerMask mask, int layer)
{
return (mask.value & (1 << layer)) != 0;
}
public static bool Contains(this LayerMask mask, GameObject go)
{
return (mask.value & (1 << go.layer)) != 0;
}
public static bool Contains(this LayerMask mask, Component component)
{
return (mask.value & (1 << component.gameObject.layer)) != 0;
}
public static LayerMask Add(this LayerMask mask, int layer)
{
return (mask.value | (1 << layer));
}
public static LayerMask Add(this LayerMask mask, GameObject go)
{
return (mask.value | (1 << go.layer));
}
public static LayerMask Add(this LayerMask mask, Component component)
{
return (mask.value | (1 << component.gameObject.layer));
}
public static LayerMask Remove(this LayerMask mask, int layer)
{
return (mask.value & ~(1 << layer));
}
public static LayerMask Remove(this LayerMask mask, GameObject go)
{
return (mask.value & ~(1 << go.layer));
}
public static LayerMask Remove(this LayerMask mask, Component component)
{
return (mask.value & ~(1 << component.gameObject.layer));
}
public static LayerMask Everything(this LayerMask mask)
{
return ~0;
}
public static LayerMask Nothing(this LayerMask mask)
{
return 0;
}
}
사용할때에는 아래와 같이 사용하면 됩니다.
[SerializeField] private LayerMask _playerLayer;
private void OnTriggerEnter(Collider other)
{
if (_playerLayer.Contains(other))
{
// 충돌한 객체가 Player
}
}

