# unity-csharp-standards > Unity 项目 C# 编码标准和规范(包含 HybridCLR 热更新限制) - Author: HY - Repository: CryBaby90/ClaudeCodeConfig - Version: 20260126004921 - Stars: 0 - Forks: 0 - Last Updated: 2026-02-06 - Source: https://github.com/CryBaby90/ClaudeCodeConfig - Web: https://mule.run/skillshub/@@CryBaby90/ClaudeCodeConfig~unity-csharp-standards:20260126004921 --- --- name: unity-csharp-standards description: Unity 项目 C# 编码标准和规范(包含 HybridCLR 热更新限制) --- # Unity C# 编码标准 > **🔴 仅适用于 Unity 项目**:如果当前不是 Unity 项目,本技能不适用。 这个技能包含了 C# 编码的标准和规范,特别针对 Unity 项目进行了优化。 --- ## ⚠️ HybridCLR 热更新限制 本项目使用 **HybridCLR** 进行热更新,热更代码有以下**严格限制**: ### 🔴 完全禁止(会导致运行时错误) ```csharp // ❌ Lambda 表达式 x => x > 1 button.onClick.AddListener(() => OnClick()) // ❌ 匿名方法/闭包 delegate() { } var captured = variable; Action action = () => captured; // ❌ LINQ Where(), Select(), OrderBy() from x in items where x > 0 select x // ❌ async/await async Task DoSomething() await Something() // ❌ yield(热更代码中) yield return new WaitForSeconds(1f) ``` **重要**:主工程 (IL2CPP) 可以使用所有这些特性!限制仅适用于热更代码。 --- ## 命名规范 | 类型 | 规范 | 示例 | |------|------|------| | 类名 | PascalCase | `public class PlayerController` | | 方法名 | PascalCase | `public void UpdateHealth()` | | 属性 | PascalCase | `public int MaxHealth { get; }` | | 公共字段 | PascalCase | `public int Score;` | | 私有字段 | camelCase | `private int playerHealth;` | | 常量 | PascalCase | `public const int MaxPlayers = 4;` | | 接口 | I + PascalCase | `public interface IDamageable` | | 枚举 | E + PascalCase | `public enum EPlayerState` | ## 访问修饰符 ```csharp // ✅ 推荐:明确指定访问级别 public class Player { public int publicField; // 公共 private int privateField; // 私有 protected int protectedField; // 派生类可访问 internal int internalField; // 程序集内可访问 } ``` ## 属性 vs 字段 ```csharp // ✅ 推荐:使用属性封装字段 private int health; public int Health { get => health; set => health = Mathf.Clamp(value, 0, MaxHealth); } // C# 3.0+ 自动属性 public int Score { get; set; } ``` ## 字符串处理 ```csharp // ❌ 避免:频繁字符串拼接 string message = "Health: " + health + " Score: " + score; // ✅ 推荐:使用 StringBuilder StringBuilder sb = new StringBuilder(); sb.Append("Health: ").Append(health); Debug.Log(sb.ToString()); // ✅ 或:字符串插值 Debug.Log($"Health: {health}, Score: {score}"); ``` ## 集合使用 ```csharp // ✅ List:动态数组 List numbers = new List(); // ✅ Dictionary:键值对 Dictionary players = new Dictionary(); // ✅ Queue:先入先出 Queue bulletPool = new Queue(); ``` ## 相关资源 - `rules/unity-coding-style.md` - Unity 编码规范 - `rules/hybridclr-restrictions.md` - HybridCLR 限制 - `Unity项目参考文档/HybridCLR快速参考.md` - 快速参考卡