t1k:unity:base:code-conventions
| Field | Value |
|---|---|
| Module | base |
| Version | 5.116.6 |
| Effort | high |
| Tools | — |
Keywords: code conventions, coding standards, naming, style
How to invoke
Section titled “How to invoke”/t1k:unity:base:code-conventionsUnity C# Code Conventions
Section titled “Unity C# Code Conventions”Triggers
Section titled “Triggers”- C# code, naming, convention, style, constant, hardcoded, magic number
- new class, new file, new component, new system, refactor
- code review, code quality, code standards
Naming Conventions (C# + Unity)
Section titled “Naming Conventions (C# + Unity)”Casing Rules
Section titled “Casing Rules”| Element | Casing | Example |
|---|---|---|
| Namespace | PascalCase | DOTSCombat |
| Class, Struct | PascalCase | AttackTimerSystem |
| Interface | IPascalCase | IHealthProvider |
| Enum | PascalCase | AttackType |
| Enum member | PascalCase | AttackType.Ranged |
| Public method | PascalCase | CalculateDamage() |
| Private method | PascalCase | ApplyKnockback() |
| Property | PascalCase | MaxHealth |
| Public field | PascalCase | DamageMultiplier |
| Private field | camelCase | attackTimer |
| Parameter | camelCase | targetEntity |
| Local variable | camelCase | closestEnemy |
Constant (const) | PascalCase | MaxStackCount |
| Static readonly | PascalCase | DefaultColor |
| Type parameter | TPascalCase | TComponent |
Unity-Specific Naming
Section titled “Unity-Specific Naming”| Element | Pattern | Example |
|---|---|---|
| MonoBehaviour | Noun/NounPhrase | PlayerController |
| IComponentData | Domain suffix | HealthData, AttackTimer |
| Tag component | Is prefix or no suffix | IsMoving, Dead |
| ISystem | Verb + System | AttackTimerSystem |
| Baker | Authoring + Baker | class HealthBaker : Baker<HealthAuthoring> |
| Authoring | Authoring suffix | HealthAuthoring |
| IAspect | Aspect suffix | CombatAspect |
| ScriptableObject | Noun | ArenaConfig |
| Editor script | Descriptive verb/noun | BattlefieldAssemblySetup |
| Test class | Tests suffix | AttackTimerSystemTests |
Library vs Demo Naming (CRITICAL)
Section titled “Library vs Demo Naming (CRITICAL)”- Library packages (
Packages/): NEVER use game/demo names. Types must be generic and reusable across games.- BAD:
ColorFitGameState,BackpackResult,BattleDemoPhase - GOOD:
QueuePuzzleGameState,GridFillSystem,CharacterMovementSystem - Test: “Would this name make sense in a completely different game?” If no → rename it.
- BAD:
- Demo code (
Assets/Demos/): Game-specific names are fine here (ColorFitCanvasUI,BattleDemoSceneSetup)
File Naming
Section titled “File Naming”- One type per file, filename matches type name:
AttackTimerSystem.cs - Keep files under 200 lines — split into partial classes or helper systems
- Editor scripts in
Editor/folder with Editor-only asmdef
No Hardcoded Values (CRITICAL)
Section titled “No Hardcoded Values (CRITICAL)”Strings — NEVER inline literals for:
Section titled “Strings — NEVER inline literals for:”- Shader names:
"Universal Render Pipeline/Lit"→ShaderConstants.UrpLit - Shader properties:
"_BaseMap"→ShaderConstants.PropBaseMap - GameObject names:
"BattlefieldArena"→private const string ArenaRootName - File paths:
"Assets/Prefabs/"→private const string PrefabFolder
Acceptable inline strings: Debug.Log(), [MenuItem("...")] attributes, nameof(), one-time errors.
Numbers — NEVER inline numeric literals:
Section titled “Numbers — NEVER inline numeric literals:”-1sentinel →private const int InvalidIndex = -1;0.1fthreshold →private const float DamageThreshold = 0.1f;2450render queue →private const int AlphaTestRenderQueue = 2450;
→ See references/constants-patterns.md for the full SharedConstants class pattern and file-local private const usage.
Code Organization
Section titled “Code Organization”Class Structure Order
Section titled “Class Structure Order”- Constants (
const,static readonly) - Static fields / Instance fields
- Constructors / Properties
- Public → Internal → Private methods
- Nested types
Assembly Definitions
Section titled “Assembly Definitions”- Each folder with distinct dependencies gets its own
.asmdef - Editor code MUST be in Editor-only asmdef (
Editor/folder) - Test code MUST have
UNITY_INCLUDE_TESTSdefine constraint
Namespace Conventions
Section titled “Namespace Conventions”- Match folder structure:
Packages/[pkg]/Runtime/Combat/→[Namespace].Combat - Editor:
[YourPackage].Editor| Tests:[YourNamespace].Tests
DOTS-Specific Conventions
Section titled “DOTS-Specific Conventions”→ Attribute ordering, lookup updates and job-field annotations: references/convention-reference.md § DOTS / ECS.
Component Design
Section titled “Component Design”- Pure data, no logic — structs implementing
IComponentData - No managed types (
string,class,List<T>) — useFixedString32Bytes/FixedString64Bytes - Tag components: empty struct (
struct Dead : IComponentData {}) - Prefer
EnableableComponentover add/remove for frequent state changes
System Design
Section titled “System Design”ISystem(struct) overSystemBase(class) for Burst compatibility[BurstCompile]on struct AND all lifecycle methods[RequireMatchingQueriesForUpdate]to skip when no matching entities- Cache
ComponentLookup<T>inOnCreate, update inOnUpdate - Hoist
SystemAPI.Time.ElapsedTimebefore foreach loops
System Ordering
Section titled “System Ordering”[UpdateInGroup(typeof(SimulationSystemGroup))][UpdateAfter(typeof(DetectionSystem))][UpdateBefore(typeof(NavigationSystemGroup))]→ See references/anti-patterns.md for the full anti-patterns table with correct alternatives.
Null Check Performance
Section titled “Null Check Performance”obj == nullonUnityEngine.Objectsubclasses invokes the overridden==operator, which calls into native code — measurably slower in hot paths- Prefer implicit bool:
if (myObj)instead ofif (myObj != null)for destroyed-object checks - NEVER use
??or?.with Unity objects — they bypass the overridden operator entirely (seet1k-unity-base-monobehaviourskill for details)
Editor Script Conventions
Section titled “Editor Script Conventions”- Menu path:
"Tools/[Package]/[Action]"— must be compile-time string literal - Always check existence before creating:
AssetDatabase.LoadAssetAtPath<T>(path) - Clean up temporaries:
Object.DestroyImmediate(tempGo) - Save after creation:
AssetDatabase.SaveAssets()+EditorSceneManager.SaveScene() - Execute Unity Editor actions via
t1k unity(menu,eval) — never ask user to run menu items manually
Reference Files
Section titled “Reference Files”| File | Content |
|---|---|
references/convention-reference.md | DI/Resolve, serialization + DOTS attribute orders, [ReadOnly]/[WriteOnly], lookup updates, lifecycle visibility, lazy init, file layout |
references/constants-patterns.md | SharedConstants class, private const, naming prefixes |
references/anti-patterns.md | Common anti-patterns table with correct alternatives |
references/unity-6000-5-api-migration.md | Unity 6000.5 obsolete-as-error recipes — EntityId, CS0619/CS0122 diagnosis, verified API map, namespace shadowing |
references/odin-sirenix-unity-6000-5.md | Odin/Sirenix on 6000.5 — the two files that fail, why AssemblyVersion lies about Odin’s version, which release fixes which half, vendor-patch bookkeeping |
Hard rules
Section titled “Hard rules”-
A namespace is not an assembly: a
usingthat compiles in a package fails in game code until the asmdef references the assembly that owns it —error CS0234: 'UIModule' does not exist in the namespace 'GameFoundation.Scripts'after acom.gdk.coreupdate, becauseUIModulemoved to its own assemblyGameFoundation.UIModuleandSlingSmash.UI.asmdefonly referencedGameFoundation.Script. Before writing ausingfrom a package, find the owning assembly (find <package> -name "*.asmdef"walking up from the file) and confirm the game asmdef lists it; copy the reference from the library’s own asmdef (grep -n GameFoundation <lib>.asmdef), do not guess the name. A package update can split or rename assemblies, so a type that resolved last week can stop resolving. Compiler errors in one file cascade: one missing assembly producesCS0246on every type from it, and an unresolved base class hides later errors (member access, overrides), so after fixing the first error re-check the whole file against the real definitions instead of waiting for the next compile. Source: SlingSmash FTUE ball-count hint session. -
TheOne.Logging.ILogger.Warning/Info/Error(string, string)areprotected internal; the callablelogger.Warning("msg")is an extension method that needsusing TheOne.Logging;— without theusing, the compiler binds the instance method and reportsCS0122: 'ILogger.Warning(string, string)' is inaccessible due to its protection level. The asmdef also needs"TheOne.Logging". Add theusingwhenever a file callsGetLogger(this).Warning/Error/Info/Debug. Source: same session. -
Before writing a new class of a kind the project already has (an FTUE action, a condition, a service), copy the
usinglist and the asmdef references from the nearest sibling (FTUEMoveIndicatorAction.csfor an FTUE action) and diff them against your file; most of the compile errors above come from re-deriving imports by hand. Source: same session. -
Code conventions enforced via
.editorconfigonly on supporting IDEs — Rider, VS Code (with C# Dev Kit), VS yes; Sublime/Vim no — pair with a CI lint to catch drift. -
Assembly definition naming has a hard 64-char path limit on Windows — long namespaces hit this in CI before any developer notices.
-
#regionblocks are an anti-pattern in modern C# — prefer extracting to partial classes; conventions should call this out explicitly. -
Timeline
PlayableDirectors revert animated properties on stop — write the end state yourself. When a director stops (naturally, or viaStop()/Evaluate()/a supersede), the bound properties snap back to their authored values, not to the clip’s last keyframe: a fade-in leaves theCanvasGroup.alphaat whatever the asset said before playback, so the view flickers back to alpha 1 (or a scale tween back to 0.9) the instant the transition ends. After the director stops, explicitly write the end state — alpha,localScale, colours — rather than assuming the clip’s last frame stuck. This also bites EditMode/editor tooling, where nothing ticks the director and an advance-to-endEvaluate()is what produces the “final” look. Pairs with the SSOT rule: regenerate a Timeline asset after editing the token it was built from, or the asset and the token silently disagree. Evidence: VanhTran.UIScreenTimelineTransition.WriteEndState(Phase 5R R-T1/R-T3). -
LayerMask.GetMask(...)is illegal in a MonoBehaviour instance field initializer —[SerializeField] private LayerMask clearanceMask = LayerMask.GetMask("Ground", "Obstacle");throwsUnityException: NameToLayer is not allowed to be called from a MonoBehaviour constructor (or instance field initializer), because the layer table isn’t available at that point in the object lifecycle. The message namesNameToLayer(whichGetMaskcalls internally) rather than theGetMaskyou actually wrote, so it doesn’t read as “your initializer is illegal”. For a[SerializeField]— whose Inspector value overrides the initializer anyway — use a literal bitmask with the derivation documented inline:= 10240; // (1<<11) Ground | (1<<13) Obstacle. Reserve thethis.mask = LayerMask.GetMask(...)-in-Awake/OnEnableform for NON-serialized fields; on a serialized one it stomps the designer’s Inspector override. -
UniTask.Preserve()supports only SEQUENTIAL re-awaits, not concurrent pre-completion awaiters — a second awaiter registering before the task completes throwsInvalidOperationException: Already continuation registered. For a run-once/await-by-many-concurrently gate (e.g. a lazy cache warm-up hit by a parallelWhenAllkey-load), back the gate with aSystem.Threading.Tasks.Taskvia.AsTask()(multi-awaiter safe) or use UniTask’sAsyncLazy— never a sharedPreserve()d UniTask. -
An opt-in
*WinFlowprovider is TWO registrations, not one — the provider’s ownRegister*()AND its feature’s core DI extension. Calling only the*WinFlowone throwsVContainerExceptionat container build and the game never boots. The providers (StreakLeaderboardWinFlowProvider,MilestoneStreakWinFlowProvider) are registeredLifetime.Singleton+AsImplementedInterfaces(), so they are discovered asIFeatureWinFlowProviderby the aggregating service — whose constructor takesIEnumerable<IFeatureWinFlowProvider>and immediately.ToArray()s it. Enumerating that collection constructs every registered provider, so a provider with an unregistered constructor dependency is a hard build failure, never a lazy null that surfaces later at its own call site.StreakLeaderboardWinFlowProvider’s constructor takesStreakLeaderboardDataController, and the only thing that registers it isRegisterStreakLeaderboard()— a different extension, in a different class, in a different assembly (…Leaderboard.Core.Scripts.DI.StreakLeaderboardVContainervs the provider’s…Leaderboard.WinFlow.DI.StreakLeaderboardWinFlowVContainer). Nothing in the provider’s own file hints that a second file must be touched, so a reader who found the one call has no signal that it is half the pair.Registration ORDER in
Configure(IContainerBuilder)is irrelevant — VContainer records every registration and constructs atBuild(), so reordering these two calls neither causes nor fixes the failure. Only presence does; do not spend a debug cycle on ordering.The Editor validator is what makes the gap silent — do not read its green as coverage.
StreakLeaderboardWinFlowValidatoryields…RegistryResult(nameof(…RegisterStreakLeaderboardWinFlow)), and that resolves toRegistryUtils.HasRegistryMethod, which reads the root lifetime scope’s source and returnscontent.Contains($"builder.{methodName}()")— a literal substring check for exactly one method name. It looks for the provider’s own call and never for the feature’s coreRegisterStreakLeaderboard(), so a project registering the provider alone validates green and then fails to boot: thegreen-that-proves-nothingshape, a check that cannot fail for the case it appears to guard. The literal match is a second trap in the same place —this.builder.Register…(), a wrapped call, or any spacing variant reads as absent when the call is present. Assert both call sites directly instead of trusting the validator:Terminal window grep -n 'RegisterStreakLeaderboard\|RegisterMilestoneStreak' Assets/Scripts/GameLifetimeScope.cs