Skip to content

t1k:cocos:base:code-conventions

FieldValue
Modulebase
Version4.51.9
Effortlow
Tools—

Keywords: ccclass, code conventions, coding standards, collider, collision group, decorator, enum, lifecycle order, naming, typescript

/t1k:cocos:base:code-conventions

Cocos Creator 3.x + TypeScript. Same game-dev mindset as the Unity C# conventions — the syntax differs, the discipline does not: self-documenting names, no hardcoded values, one responsibility per file, decouple via signals, clean up on teardown.

  • TypeScript code, naming, convention, style, constant, hardcoded, magic number
  • new class, new file, new component, new service, new controller, refactor
  • code review, code quality, code standards, @ccclass, SignalBus
ElementCasingExample
Class, Component, ServicePascalCase + semantic suffixColorService, TimerComponent
InterfacePascalCase, NO I prefixHealthProvider (not IHealthProvider)
Type aliasPascalCaseSpawnOptions
EnumPascalCase nameAttackType
Enum memberPascalCase name, lowercase string value (Brown = 'brown') — unless the enum is editor-exposed via @property, which requires numeric members + Enum() (see § Decorators)Brown = 'brown'
Public method / propertycamelCasecalculateDamage(), maxHealth
Private methodcamelCaseapplyKnockback()
Private field_camelCase (underscore prefix)_attackTimer
Parameter / localcamelCasetargetNode, closestEnemy
Constant (module/config)UPPER_SNAKE_CASEMAX_STACK_COUNT
readonly config valueUPPER_SNAKE_CASE or camelCasereadonly SPAWN_RATE = 2
Generic type parameterTPascalCaseTComponent
Callback methodon* or handle* prefixonWeaponPlaced, handleTimerEnd

Note — deviates from some TS style guides on purpose: private fields use the underscore prefix (_camelCase). This is the studio standard for Cocos/TS and is mandatory. Enum string values are lowercase for stable serialization (BROWN = 'brown').

ElementPatternExample
Component (UI / scene-attached)Noun + Component/View/ControllerPlayerController, HpBarView
Service (business logic singleton)Noun + ServiceColorService, AudioService
Signal classNoun + SignalWinSignal, ColorPickedSignal
Config / ScriptableObject-likeNoun + ConfigGameConfig, ArenaConfig
File{Feature}{Suffix}.ts (matches type)ColorService.ts, TimerComponent.ts

Reusable Framework vs Game-Specific Code (CRITICAL)

Section titled “Reusable Framework vs Game-Specific Code (CRITICAL)”
  • Framework / shared packages (e.g. PLAGameFoundation, shared utils/): NEVER bake a game/demo name into a type. Names must read correctly in a completely different game.
    • BAD: ColorFitSignalBus, BeadsOutPool
    • GOOD: SignalBus, ObjectPool<T>
    • Test: “Would this name make sense in another game?” If no → rename.
  • Game-specific code (assets/scripts/{Game}/): game names are fine here (ColorFitBoard, BeadsOutCanvasUI).
  • Node / prefab names: find('Canvas/HpBar') → extract the path to a const
  • Bundle / asset keys, event names, scene names → named const or config
  • Pool keys → reuse the type name, not a magic string

Acceptable inline strings: console.log(...), @ccclass('ClassName') decorator arg, error messages thrown once.

Numbers — NEVER inline numeric literals:

Section titled “Numbers — NEVER inline numeric literals:”
  • -1 sentinel → const INVALID_INDEX = -1;
  • 0.1 threshold → const DAMAGE_THRESHOLD = 0.1;
  • Tween durations, spawn counts, sizes → GameConfig or a file-local const

→ See references/constants-patterns.md for the GameConfig object pattern, module constants, and file-local const usage.

  • One type per file; filename matches the type: ColorService.ts.
  • Keep files under 200 lines — split into helper classes, extract utilities, compose over inherit.
  1. const { ccclass, property } = _decorator; (top of file)
  2. Constants (static readonly / module const)
  3. @property serialized fields, then private fields
  4. Lifecycle methods in order (see below)
  5. Public → private methods
  6. Callbacks (on* / handle*)
assets/scripts/{Game}/
├── services/ # Business-logic singletons
├── UI/ # Components, views, controllers
├── Data/ # Models, enums, configs
├── Signal/ # Signal classes + shared signalBus export
├── utils/ # Static helpers
└── constant/ # Named constants
  • Destructure once at top: const { ccclass, property } = _decorator;
  • @ccclass('ClassName') on every component class.
  • @property(Type) only for editor-exposed fields — not every private field.
  • An enum used as a @property type MUST have NUMERIC members and be registered with Enum(X) from cc. This overrides the lowercase-string enum guidance in § Naming Conventions for editor-exposed enums only. Two distinct failure shapes — read the Gotchas entry before authoring any @property({ type: SomeEnum }) field:
import { _decorator, Component, Enum } from 'cc';
const { ccclass, property } = _decorator;
// ✅ numeric members + Enum() registration — the Inspector renders a dropdown
export enum PartSlotType { HEAD_TOP = 0, NECK = 1, FACE = 2 }
Enum(PartSlotType);
@ccclass('MonsterVisualizer')
export class MonsterVisualizer extends Component {
@property({ type: PartSlotType }) slotType: PartSlotType = PartSlotType.FACE;
}
// ❌ string members — no dropdown, the field deserialises as its class default,
// and `slotType === PartSlotType.NECK` never matches in any build
export enum PartSlotType { HEAD_TOP = 'head-top', NECK = 'neck', FACE = 'face' }
  • Registration is what makes the engine treat the object as an enumeration at all: Enum.isEnum(X) is literally a hasOwnProperty('__enums__') check, and Enum.getList(X) asserts it before returning the enumerator list the Inspector builds its dropdown from (cc/core/value-types/enum.ts, Cocos Creator 3.8.7). Enum(X) / ccenum(X) are the only things that add __enums__ — every engine enum is registered this way.
  • Enum() takes a local enum literal at module top level — never an imported barrel/registry value, whose load-order throw de-registers every @ccclass in the package. That gotcha is owned by the t1k-cocos-playable-editor-tools skill (its hard-rules reference).

onLoad → onEnable → start → update → onDisable → onDestroy

  • Lazy init: this._field ??= new Foo(); (in onLoad/start, not update).
  • Subscribe in onLoad/onEnable; unsubscribe in onDestroy/onDisable — always pair.
  • Decouple systems with signalBus.subscribe/unsubscribe() — NOT direct cross-component calls.
  • MUST use named methods (arrow-function class fields), NOT inline lambdas.
  • Reason: unsubscribe() uses indexOf() on the handler ref; a fresh inline lambda has a new ref every call → it can never be removed → leak.
private onColorPicked = (s: ColorPickedSignal): void => { /* ... */ };
onLoad() { signalBus.subscribe(ColorPickedSignal, this.onColorPicked); }
onDestroy() { signalBus.unsubscribe(ColorPickedSignal, this.onColorPicked); }
  • Service — business logic, reusable, singleton (private static _instance + static get instance(), set in onLoad).
  • Component — UI / scene-attached, extends Component.
  • Controller — orchestration + state management.
  • Guard clauses for null safety — early return, not nested ifs.
  • readonly for config values — prevents runtime mutation.
  • Prefer explicit types on public surfaces; avoid any (use unknown + narrowing).
  • enum values are lowercase strings for serialization stability — except an enum exposed through @property, which must be numeric and Enum()-registered (see § Decorators).
  • Extract magic numbers to GameConfig or a local const.

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

FileContent
references/constants-patterns.mdGameConfig object, module constants, file-local const, naming prefixes
references/anti-patterns.mdCommon Cocos/TS anti-patterns table with correct alternatives
references/physics-collision-groups.mdWhere a collider’s collision group actually lives (per-node shared body), and when a group bit test may stand in for getComponent
references/physics-cannon-backend-traps.mdFour silent cannon.js failures: the unimplemented cc.CapsuleCollider, damping > 1 going NaN on the first step, a disabled RigidBody that leaves its colliders simulating, and a clamped friction impulse that stops heavy bodies short

The hardcode sweep is mechanical; deciding where a literal belongs is not. Routing SSOT: theonekit-core/.claude/modules/t1k-orchestration/rules/orchestration-rules.md § “Task-Type → Agent Routing”.

StepAgent
Run hardcode-scan.cjs and label each finding hardcoded-number / hardcoded-string per its own rule tablet1k-list-classifier
Choose a named const, an existing config field or the parameter layer for a flagged literalt1k-cocos-base-developer — reasoning tier, per references/constants-patterns.md
  • Inline lambdas in signalBus.subscribe leak — unsubscribe matches by reference via indexOf; a new lambda each call never matches. Always bind a named arrow-function class field. Most common Cocos memory-leak source.
  • Forgetting onDestroy cleanup — timers (this.unschedule), tweens (Tween.stopAllByTarget), and signal handlers all leak across scene reloads if not torn down. Pair every subscribe/schedule with a teardown.
  • node.active = false does NOT fire onDestroy — it fires onDisable. Put reversible teardown in onDisable, permanent teardown in onDestroy. Confusing the two double-subscribes on re-enable.
  • @property without a type on a node ref serializes as null silently — a ref never dragged in the editor is null at runtime with no error. Guard-clause every @property node ref before use.
  • A bare @property with no explicit type AND a falsy default ('', 0, false, null) is silently DROPPED from CCClass metadata entirely — worse than the null case above: it never appears in the Inspector at all and can never be wired in the scene, with no error anywhere. A non-falsy default (e.g. = 0.1) infers its type fine. Always pass an explicit type for anything that might default falsy: @property({ type: CCString }) for strings, @property(AnimationClip) for asset refs. Observed on four string clip-name fields left at = '' in WeaponAnimator.ts (AnimalHunterWildPLA, 2026-09-12, Cocos Creator 3.8.7) — invisible in the editor until explicitly typed.
  • _decorator must be imported from cc — import { _decorator, Component, Node } from 'cc';. Copy-pasting a class without the import gives a cryptic decorator error.
  • Enum numeric-vs-string drift — mixing numeric and string enum members breaks serialization round-trips. Keep an enum all-string (= 'brown') or all-numeric, never mixed.
  • A STRING enum behind @property silently serializes as the field’s declared default, so every branch testing it never fires — the silent twin of the falsy-default drop above, and the one that survives code review because nothing errors: tsc passes, the type-checker agrees, and the wrong value is simply what the property holds. The field gets no Inspector dropdown, is not authorable in the editor, and deserialises as the default written on the field — so any === test against it is dead code in every build. Fix: numeric members + Enum(X) from cc at module top level, per § Decorators. Observed 2026-09-15 in consumer Mix-Monster: PartSlotType was a string enum behind @property({ type: PartSlotType }), so layerOf()’s slotType === PartSlotType.NECK test never matched and every neck accessory drew in front of the body — caught by code review, never by tsc.
  • An enum object NOT passed through Enum() is rejected as a @property type in the editor — the editor logs Please define 'type' parameter of {Class}.{field} as the constructor of [object Object] once per @property({ type: EnumType }) site. This is the LOUD half and it is still easy to miss: the message names [object Object], never the enum, and it is an editor-console error — a browser-preview or shipped build surfaces nothing, and a project already drowning in unrelated module-resolution errors buries it further. Fix each site’s enum by registering it: Enum(X) from cc. Observed on Mix-Monster’s @property({ type: MonsterPartType }) sites (ItemPanelController:11, PartItem:51, SlotItem:22) — pre-existing, not a regression: the pre-reset editor log carried 10 occurrences including a class already deleted from the branch. The same repo holds the correct pattern twice (EndCardMode.ts:30, PartSlotType), which is why review — not the compiler — is what catches it.
  • A collider’s collision group comes from its node, not from the collider — Collider serialises no group of its own; getGroup() forwards to the per-node shared body, whose group is that node’s RigidBody.group. So collider.getGroup() & SOME_BIT is a valid stand-in for getComponent(SomeClass) only when the RigidBody and the collider sit on the same node — a collider one level down with no RigidBody of its own reports PhysicsGroup.DEFAULT, and every group predicate goes quietly false with no error and no failing test. See references/physics-collision-groups.md before swapping a component test for a group test.
  • On the cannon.js backend, cc.CapsuleCollider does not exist at runtime and damping must be < 1 — the editor accepts both, and both fail with no error: a capsule deserialises to a stub with _shape.impl === null so the body carries zero shapes, and cannon damps by Math.pow(1 - damping, dt), so linearDamping: 2 is Math.pow(-1, 1/60) = NaN on the very first step. The NaN reaches the node through syncPhysicsToScene and reads back as exactly (0,0,0) — indistinguishable from a spawn bug. Tell: node.scale is (1,1,1) while node.worldScale is (0,0,0). No runtime repair exists; fix the prefab and reload. See references/physics-cannon-backend-traps.md.
  • rigidBody.enabled = false does NOT take a node out of the physics simulation — RigidBody and Collider are independent components sharing one per-node CannonSharedBody, and the collider holds its own reference. Disabling the body alone leaves that shared body in physicsWorld.bodies, still DYNAMIC, still stepped, still overwriting the node’s world transform every frame. Bites hardest when porting from Rapier, where setEnabled(false) takes the colliders with it. Disable every Collider too — and restore both, or a pooled node respawns with no collision shape. Verify by physicsWorld.bodies.length dropping, never by the enabled flag. See references/physics-cannon-backend-traps.md.
  • This is guidance, not an enforced gate — pair with a linter (.eslintrc) + CI to catch drift; a convention skill alone does not block violations.
  • Quat.fromEuler is YZX, not XYZ — porting a rotation from a three.js/Unity-style flat quad (rotation.x = -PI/2, rotation.z = spin) must put the spin in the Y slot instead: Quat.fromEuler(out, -90, spin, 0). Putting spin in the z argument tilts the quad instead of spinning it — no error, no warning, just the wrong axis.

If unsure about a convention not covered here, ask the user for their preference and update this skill. Conventions grow from real decisions.