1. Extension Method란?


2. 기본 문법

// 1) 반드시 static 클래스 안에
public static class MyExtensions
{
    // 2) static 메서드
    public static 반환형 Foo(this 대상타입 obj, /* 나머지 파라미터 */)
    {
        // obj를 이용한 유틸리티 로직
    }
}

// 사용 예
string s = "hello";
int len = s.Foo();    // 실제론 MyExtensions.Foo(s);


3. Vector3 조작용 Extension

3.1. With – 특정 컴포넌트만 바꾸기


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);
    }
}

3.2. Add – 특정 컴포넌트만 더하기

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));
}

4. 컴포넌트 자동 추가 – GetOrAddComponent

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>();
    }
}