this T obj 형태로 대상을 명시하면, obj.메서드()처럼 호출 가능obj.DoSomething() 형태로 간결하게 사용obj.Ext1().Ext2() 형태로 연쇄 호출 가능// 1) 반드시 static 클래스 안에
public static class MyExtensions
{
// 2) static 메서드
public static 반환형 Foo(this 대상타입 obj, /* 나머지 파라미터 */)
{
// obj를 이용한 유틸리티 로직
}
}
// 사용 예
string s = "hello";
int len = s.Foo(); // 실제론 MyExtensions.Foo(s);
public static class Vector3Extensions
{
// 기본값 null ⇒ 변경하고 싶은 축만 지정
public static Vector3 With(
this Vector3 v,
float? x = null,
float? y = null,
float? z = null
)
{
return new Vector3(x ?? v.x, y ?? v.y, z ?? v.z);
}
}
사용 예
// y축만 2.5로 바꾸고 싶을 때
transform.position = transform.position.With(y: 2.5f);
public static Vector3 Add(
this Vector3 v,
float? x = null,
float? y = null,
float? z = null
)
{
return new Vector3(v.x + (x ?? 0), v.y + (y ?? 0), v.z + (z ?? 0));
}
사용 예
// x축 +5, y축 +1 만큼 이동
transform.position = transform.position.Add(x:5f, y:1f);
using UnityEngine;
public static class GameObjectExtensions
{
// T : Component 제약
public static T GetOrAddComponent<T>(this GameObject go) where T : Component
{
var comp = go.GetComponent<T>();
if (comp != null) return comp;
return go.AddComponent<T>();
}
}
용도
사용 예
// PowerOrb에 BobUpDown 컴포넌트를 반드시 붙여 실행
var bob = powerOrb.GetOrAddComponent<BobUpDown>();
bob.enabled = true;