Skip to content

t1k:unity:base:code-conventions

FieldValue
Modulebase
Version5.116.6
Efforthigh
Tools—

Keywords: code conventions, coding standards, naming, style

/t1k:unity:base:code-conventions

  • C# code, naming, convention, style, constant, hardcoded, magic number
  • new class, new file, new component, new system, refactor
  • code review, code quality, code standards
ElementCasingExample
NamespacePascalCaseDOTSCombat
Class, StructPascalCaseAttackTimerSystem
InterfaceIPascalCaseIHealthProvider
EnumPascalCaseAttackType
Enum memberPascalCaseAttackType.Ranged
Public methodPascalCaseCalculateDamage()
Private methodPascalCaseApplyKnockback()
PropertyPascalCaseMaxHealth
Public fieldPascalCaseDamageMultiplier
Private fieldcamelCaseattackTimer
ParametercamelCasetargetEntity
Local variablecamelCaseclosestEnemy
Constant (const)PascalCaseMaxStackCount
Static readonlyPascalCaseDefaultColor
Type parameterTPascalCaseTComponent
ElementPatternExample
MonoBehaviourNoun/NounPhrasePlayerController
IComponentDataDomain suffixHealthData, AttackTimer
Tag componentIs prefix or no suffixIsMoving, Dead
ISystemVerb + SystemAttackTimerSystem
BakerAuthoring + Bakerclass HealthBaker : Baker<HealthAuthoring>
AuthoringAuthoring suffixHealthAuthoring
IAspectAspect suffixCombatAspect
ScriptableObjectNounArenaConfig
Editor scriptDescriptive verb/nounBattlefieldAssemblySetup
Test classTests suffixAttackTimerSystemTests
  • 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.
  • Demo code (Assets/Demos/): Game-specific names are fine here (ColorFitCanvasUI, BattleDemoSceneSetup)
  • 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
  • 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:”
  • -1 sentinel → private const int InvalidIndex = -1;
  • 0.1f threshold → private const float DamageThreshold = 0.1f;
  • 2450 render queue → private const int AlphaTestRenderQueue = 2450;

→ See references/constants-patterns.md for the full SharedConstants class pattern and file-local private const usage.

  1. Constants (const, static readonly)
  2. Static fields / Instance fields
  3. Constructors / Properties
  4. Public → Internal → Private methods
  5. Nested types
  • 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_TESTS define constraint
  • Match folder structure: Packages/[pkg]/Runtime/Combat/ → [Namespace].Combat
  • Editor: [YourPackage].Editor | Tests: [YourNamespace].Tests

→ Attribute ordering, lookup updates and job-field annotations: references/convention-reference.md § DOTS / ECS.

  • Pure data, no logic — structs implementing IComponentData
  • No managed types (string, class, List<T>) — use FixedString32Bytes/FixedString64Bytes
  • Tag components: empty struct (struct Dead : IComponentData {})
  • Prefer EnableableComponent over add/remove for frequent state changes
  • ISystem (struct) over SystemBase (class) for Burst compatibility
  • [BurstCompile] on struct AND all lifecycle methods
  • [RequireMatchingQueriesForUpdate] to skip when no matching entities
  • Cache ComponentLookup<T> in OnCreate, update in OnUpdate
  • Hoist SystemAPI.Time.ElapsedTime before foreach loops
[UpdateInGroup(typeof(SimulationSystemGroup))]
[UpdateAfter(typeof(DetectionSystem))]
[UpdateBefore(typeof(NavigationSystemGroup))]

→ See references/anti-patterns.md for the full anti-patterns table with correct alternatives.

  • obj == null on UnityEngine.Object subclasses invokes the overridden == operator, which calls into native code — measurably slower in hot paths
  • Prefer implicit bool: if (myObj) instead of if (myObj != null) for destroyed-object checks
  • NEVER use ?? or ?. with Unity objects — they bypass the overridden operator entirely (see t1k-unity-base-monobehaviour skill for details)
  • 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
FileContent
references/convention-reference.mdDI/Resolve, serialization + DOTS attribute orders, [ReadOnly]/[WriteOnly], lookup updates, lifecycle visibility, lazy init, file layout
references/constants-patterns.mdSharedConstants class, private const, naming prefixes
references/anti-patterns.mdCommon anti-patterns table with correct alternatives
references/unity-6000-5-api-migration.mdUnity 6000.5 obsolete-as-error recipes — EntityId, CS0619/CS0122 diagnosis, verified API map, namespace shadowing
references/odin-sirenix-unity-6000-5.mdOdin/Sirenix on 6000.5 — the two files that fail, why AssemblyVersion lies about Odin’s version, which release fixes which half, vendor-patch bookkeeping
  • A namespace is not an assembly: a using that 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 a com.gdk.core update, because UIModule moved to its own assembly GameFoundation.UIModule and SlingSmash.UI.asmdef only referenced GameFoundation.Script. Before writing a using from 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 produces CS0246 on 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) are protected internal; the callable logger.Warning("msg") is an extension method that needs using TheOne.Logging; — without the using, the compiler binds the instance method and reports CS0122: 'ILogger.Warning(string, string)' is inaccessible due to its protection level. The asmdef also needs "TheOne.Logging". Add the using whenever a file calls GetLogger(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 using list and the asmdef references from the nearest sibling (FTUEMoveIndicatorAction.cs for 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 .editorconfig only 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.

  • #region blocks 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 via Stop()/Evaluate()/a supersede), the bound properties snap back to their authored values, not to the clip’s last keyframe: a fade-in leaves the CanvasGroup.alpha at 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-end Evaluate() 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.UI ScreenTimelineTransition.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"); throws UnityException: 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 names NameToLayer (which GetMask calls internally) rather than the GetMask you 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 the this.mask = LayerMask.GetMask(...) -in-Awake/OnEnable form 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 throws InvalidOperationException: Already continuation registered. For a run-once/await-by-many-concurrently gate (e.g. a lazy cache warm-up hit by a parallel WhenAll key-load), back the gate with a System.Threading.Tasks.Task via .AsTask() (multi-awaiter safe) or use UniTask’s AsyncLazy — never a shared Preserve()d UniTask.

  • An opt-in *WinFlow provider is TWO registrations, not one — the provider’s own Register*() AND its feature’s core DI extension. Calling only the *WinFlow one throws VContainerException at container build and the game never boots. The providers (StreakLeaderboardWinFlowProvider, MilestoneStreakWinFlowProvider) are registered Lifetime.Singleton + AsImplementedInterfaces(), so they are discovered as IFeatureWinFlowProvider by the aggregating service — whose constructor takes IEnumerable<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 takes StreakLeaderboardDataController, and the only thing that registers it is RegisterStreakLeaderboard() — a different extension, in a different class, in a different assembly (…Leaderboard.Core.Scripts.DI.StreakLeaderboardVContainer vs 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 at Build(), 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. StreakLeaderboardWinFlowValidator yields …RegistryResult(nameof(…RegisterStreakLeaderboardWinFlow)), and that resolves to RegistryUtils.HasRegistryMethod, which reads the root lifetime scope’s source and returns content.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 core RegisterStreakLeaderboard(), so a project registering the provider alone validates green and then fails to boot: the green-that-proves-nothing shape, 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