C# Extensions

0 阅读3分钟

Unity C# Extensions API 文档

Overview

本库提供了一组用于 Unity 项目开发的 C# 扩展方法(Extension Methods) ,用于提升代码可读性、减少重复代码,并优化常见开发流程,例如:

  • 组件管理
  • 数值计算
  • Transform 操作
  • Vector 操作
  • 字符串处理
  • 集合操作
  • 游戏对象管理
  • Rigidbody 控制
  • 协程与延迟执行

适用场景:

  • Gameplay 开发
  • 工具脚本
  • AI / FSM
  • UI 系统
  • 数学计算
  • 数据处理

1. ComponentExtensions

AddComponent()

T AddComponent<T>(this Component component)

说明

向当前组件所属的 GameObject 添加组件。

示例

var rigidbody = playerMovement.AddComponent<Rigidbody>();

GetOrAddComponent()

T GetOrAddComponent<T>(this Component component)

说明

如果组件存在则获取,否则自动添加。

示例

var collider = transform.GetOrAddComponent<BoxCollider>();

常用于初始化组件。


HasComponent()

bool HasComponent<T>(this Component component)

说明

判断组件是否存在。

示例

if (player.HasComponent<Rigidbody>())
{
    Debug.Log("Player has Rigidbody");
}

2. DecimalExtensions

TruncateTo()

decimal TruncateTo(this decimal value, uint digits)

说明

截断小数位,不进行四舍五入。

示例

decimal value = 3.14159m.TruncateTo(2);
// 3.14

3. DictionaryExtensions

AddOrUpdate()

void AddOrUpdate<TKey, TValue>(
    this Dictionary<TKey, TValue> dictionary,
    TKey key,
    TValue value)

说明

如果 Key 存在则更新,否则添加。

示例

scores.AddOrUpdate("player1", 100);

4. FloatExtensions

RandomBias()

float RandomBias(this float value, float range, bool useNegativeBias = true)

说明

对数值添加随机偏移。

常用于:

  • AI 行为随机化
  • 移动速度波动
  • 动画随机变化

示例

float speed = 5f.RandomBias(0.5f);

Round()

float Round(this float value, int digits = 0)

示例

float result = 3.14159f.Round(2);
// 3.14

IsApproximatelyEqual()

bool IsApproximatelyEqual(float other, float tolerance = 0.0001f)

用于浮点比较。


ToPercentage()

float ToPercentage(this float value, float total)

示例

float percent = currentHealth.ToPercentage(maxHealth);

5. GameObjectExtensions

GetOrAddComponent()

T GetOrAddComponent<T>(this GameObject gameObject)

示例

var audioSource = gameObject.GetOrAddComponent<AudioSource>();

ToggleActive()

void ToggleActive(this GameObject gameObject)

示例

panel.ToggleActive();

HasComponent()

检查 GameObject 是否包含组件。


DestroyAllChildren()

销毁所有子物体。

container.DestroyAllChildren();

AddComponentIfMissing()

确保组件存在。

gameObject.AddComponentIfMissing<Rigidbody>();

6. IntExtensions

ToAbbreviatedString()

string ToAbbreviatedString(this int value, uint digits = 0)

示例

1500.ToAbbreviatedString()
// 1.5k

适用于:

  • 金币
  • 分数
  • 数量 UI

RoundToMultipleOf()

int RoundToMultipleOf(this int value, int binSize)

示例

37.RoundToMultipleOf(10)
// 40

7. ListExtensions

GetRandomItem()

T GetRandomItem<T>(this IList<T> list)

示例

var enemy = enemies.GetRandomItem();

RemoveLastItem()

void RemoveLastItem<T>(this IList<T> list, int count = 1)

RemoveNulls()

void RemoveNulls<T>(this List<T> list)

8. MonoBehaviourExtensions

DelayedExecution()

void DelayedExecution(
    this MonoBehaviour behaviour,
    float delay,
    Action callback)

示例

this.DelayedExecution(2f, () =>
{
    SpawnEnemy();
});

用于:

  • UI延迟
  • AI行为
  • 动画事件

GetOrAddComponent()

T GetOrAddComponent<T>(this MonoBehaviour behaviour)

AddComponentIfMissing()

T AddComponentIfMissing<T>(this MonoBehaviour behaviour)

9. ObjectExtensions

DestroyGameObject()

void DestroyGameObject(this Object value)

示例

enemy.DestroyGameObject();

10. RigidbodyExtensions

ChangeDirection()

void ChangeDirection(this Rigidbody rigidbody, Vector3 direction)

说明

保持速度大小不变,仅改变方向。

示例

rigidbody.ChangeDirection(Vector3.forward);

适用于:

  • 子弹
  • 物理角色
  • AI移动

11. StringExtensions

ToEnum()

T ToEnum<T>(this string value)

示例

DayOfWeek day = "Monday".ToEnum<DayOfWeek>();

Truncate()

string Truncate(this string value, int maxLength)

ToTitleCase()

string ToTitleCase()

IsNullOrEmpty()

bool IsNullOrEmpty()

IsNullOrWhiteSpace()

bool IsNullOrWhiteSpace()

Reverse()

string Reverse()

RemoveWhitespace()

string RemoveWhitespace()

ToCamelCase()

string ToCamelCase()

SplitCamelCase()

string SplitCamelCase()

示例:

"PlayerHealthBar".SplitCamelCase()
// Player Health Bar

12. TransformExtensions

SetLocalPosition()

void SetLocalPosition(float? x = null, float? y = null, float? z = null)

示例

transform.SetLocalPosition(x: 2);

SetWorldPosition()

transform.SetWorldPosition(y: 10);

SetPositionX / Y / Z

transform.SetPositionX(5);
transform.SetPositionY(3);
transform.SetPositionZ(-2);

SetLocalEulerAngles()

transform.SetLocalEulerAngles(x: 30, y: 60);

SetWorldEulerAngles()

transform.SetWorldEulerAngles(z: 90);

13. Vector2Extensions

WithX()

Vector2 WithX(float x)

示例

vector = vector.WithX(10);

WithY()

Vector2 WithY(float y)

SetMagnitude()

Vector2 SetMagnitude(float magnitude)

示例

velocity = velocity.SetMagnitude(10);

14. Vector3Extensions

WithX / WithY / WithZ

vector = vector.WithX(5);
vector = vector.WithY(10);
vector = vector.WithZ(3);

支持:

  • 指定数值
  • Transform
  • Vector3

示例:

vector = vector.WithY(targetTransform);

WithRandomBias()

Vector3 WithRandomBias(float bias)
Vector3 WithRandomBias(Vector3 bias)

示例

position = position.WithRandomBias(0.5f);

用于:

  • 敌人巡逻
  • 随机生成
  • 粒子系统

GetClosest()

Vector3 GetClosest(IEnumerable<Vector3> positions)

示例

Vector3 closest = myPosition.GetClosest(enemyPositions);

优化点:

使用 平方距离计算(性能更好)


推荐使用场景(实际项目)

最常用的扩展其实是这几个:

开发中出现频率最高:

GetOrAddComponent
WithX / WithY / WithZ
SetLocalPosition
RandomBias
GetRandomItem
DelayedExecution
DestroyAllChildren
ToAbbreviatedString
SplitCamelCase

如果是 VR项目 / 交互项目(你现在的项目类型) ,最有价值的是:

TransformExtensions
VectorExtensions
ComponentExtensions
MonoBehaviourExtensions

因为可以明显减少:

  • Transform重复代码
  • GetComponent调用
  • 协程样板代码

如果你愿意,我可以帮你把这份文档升级成 完整专业版(适合开源项目) ,包括:

  • 完整命名空间结构
  • 每个扩展的源码结构
  • Unity最佳实践
  • 性能说明
  • 使用模式(Best Practices)
  • 推荐组合用法
  • 常见错误示例

会比现在这个再专业一个级别。