Skip to content

t1k:unity:base:game-patterns

FieldValue
Modulebase
Version5.116.6
Effortmedium
Tools—

Keywords: 4-layer architecture, application layer, architecture, asmdef strict, circular dependency, clean architecture, design patterns, domain layer, friction cache, game patterns, hexagonal architecture, infrastructure layer, module contract, ports and adapters, presentation layer, registration override, sidewaysFriction, vcontainer composition root, wheel-friction

/t1k:unity:base:game-patterns

  • Implementing game mechanics or systems (MonoBehaviour context)
  • Setting up object pooling, state machines
  • Designing save/load systems
  • Managing scenes (additive loading, transitions)
  • Handling input (New Input System, touch)
  • Creating data-driven systems with ScriptableObjects
  • Refactoring a god-MonoBehaviour into 4-layer Clean Architecture, or scaffolding a new feature module under it (see theonekit-core t1k-game-arch for the engine-agnostic doctrine)
TaskReference
Object pooling, state machines, command, procedural dynamic meshCore Patterns (references/core-patterns.md)
ScriptableObjects, config, save systemsData & Persistence (references/data-persistence.md)
Scene management, input, coroutine alternativesSystems (references/game-systems.md)
Project hierarchy, scene architecture, canvas configMobile Setup (references/mobile-setup.md)
Player settings, quality/physics/audio, perf budgetsMobile Optimization (references/mobile-optimization.md)
VContainer registration override, circular dependencyVContainer Registration Override (references/vcontainer-registration-override.md)
4-layer Clean Architecture (Domain/Application/Presentation/Infrastructure), asmdef strict, VContainer composition root, NUnitClean Architecture (4-Layer) (references/clean-architecture-4layer.md)
Scaffolding a new Clean-Architecture feature module (asmdef stubs)Clean Architecture Scaffold (references/clean-architecture-scaffold.md)

Note: System.Linq is forbidden in runtime code (GC alloc). Use foreach in runtime; System.Linq only in editor/tests.

  1. Pool everything that spawns/despawns frequently — Use UnityEngine.Pool.ObjectPool<T>
  2. ScriptableObjects for data — Config, items, levels, balancing — NOT MonoBehaviours
  3. State machines for complex state — Game states, AI, UI flow
  4. New Input System — Always use for cross-platform (touch + gamepad + keyboard)
  5. UniTask over coroutines — Async/await with cancellation support
  6. VContainer for DI — All services via constructor injection (see theone-studio-patterns)
  7. No System.Linq at runtime — GC alloc; use foreach or ZLinq (see t1k-unity-dots-core-zlinq skill)
public sealed class BulletPool : IInitializable, IDisposable
{
readonly ObjectPool<Bullet> _pool;
public BulletPool(Bullet prefab)
{
_pool = new ObjectPool<Bullet>(
createFunc: () => Object.Instantiate(prefab),
actionOnGet: b => b.gameObject.SetActive(true),
actionOnRelease: b => b.gameObject.SetActive(false),
defaultCapacity: 20, maxSize: 100);
}
public Bullet Get() => _pool.Get();
public void Release(Bullet b) => _pool.Release(b);
public void Dispose() => _pool.Dispose();
}
public abstract class GameState { public abstract UniTask Enter(); public abstract void Exit(); }
// States: MenuState, PlayState, PauseState, GameOverState
// Managed via GameStateService with VContainer
  • Unity fake null: Never use ?? or is null with UnityEngine.Object — Unity overrides == to detect destroyed objects, but ??/is null bypasses this and treats destroyed objects as non-null

  • Coroutine on disabled GO: StartCoroutine() throws if the MonoBehaviour or its GameObject is inactive. Check gameObject.activeInHierarchy before starting

  • ScriptableObject shared in builds: SO assets are shared instances — mutating fields at runtime affects all references. Clone with Instantiate() if per-instance data is needed

  • Per-frame polyline geometry (rope/tube/trail): build ONE dynamic Mesh (MarkDynamic() + bounded SetVertices/SetIndices(array, start, length) overloads, mitered rings with a parallel-transport frame to avoid twist) — do NOT Graphics.RenderMeshInstanced N built-in cylinders (~3000 vs ~210 verts, and primitives leave gaps at corners). Per-instance texture → MaterialPropertyBlock _BaseMap, not a material instance. See Core Patterns → Procedural Dynamic Mesh (references/core-patterns.md)

  • Wheel friction cache poisoned by Awake grip multiply: Multiplying WheelCollider.sidewaysFriction.stiffness in code at Awake (a grip multiplier) BEFORE a later lazily-populated friction-default cache (e.g. CarVehicle.CacheDefaultFriction) runs poisons that cache — it captures the already-inflated value as the “default” baseline, so runtime zone/upgrade friction multipliers then scale off the wrong baseline (e.g. 1.5x too high). Fix (SSOT): author the baseline grip on the WheelCollider prefab (single source of truth) and remove the Awake code-side multiply. If a runtime multiplier knob is genuinely required, capture the defaults (call the cache) BEFORE any code-side multiply. Prefab-SSOT is preferred.

  • Static-class GameObject spawners need explicit teardown on EVERY end-of-run path (2026-05-19): a static-class spawner holds its spawned GameObjects in static fields, and static fields survive a runtime Restart in a build (there is no domain reload outside the Editor). So the GameObjects orphan on restart unless every end-of-run path calls ClearAll(). Audit checklist: (1) run-failure path, (2) run-completion/win path, (3) restart-button handler, (4) safety net at run-begin (if (root != null) Destroy(root)). Do NOT rely on scene unload alone. Evidence: f4f00138 — a HeroVisualSpawner needed teardown wiring added after the static-class approach was chosen in 8343b5d8.

  • VContainer duplicate registration ≠ last-wins: two RegisterInstance/Register<T>() calls for the same concrete type do NOT override — VContainer throws VContainerException: Conflict implementation type at container build (boot crash). Library-default + consumer-override needs IContainerBuilder.Exists guard on the library side AND the consumer registering BEFORE calling the library’s Register* extension. See VContainer Registration Override (references/vcontainer-registration-override.md) for the ordering pattern and the circular-dependency (VContainerException: Circular dependency detected!) fix via SignalBus.

  • The ObjectPool<T> pattern above is generic Unity, not the studio-mandated runtime spawner. Any runtime Mono spawn (new GameObject/Instantiate replacement) MUST go through TheOne.Pooling.IObjectPoolManager, never a hand-rolled UnityEngine.Pool.ObjectPool<T> — see rules/mono-pool-spawn-unity.md for the ban and docs/mono-pool-spawn-unity.md for the full 7-step recipe, the key-vs-prefab Spawn asymmetry trap (Spawn(key,…) throws if unloaded; Spawn(prefab,…) auto-loads), and reference implementations.

  • t1k-unity-base-code-conventions — Code quality, naming conventions
  • t1k-unity-ui-mobile-ui — UI state management, input handling
  • t1k-unity-dots-core-zlinq — Zero-alloc LINQ alternative for runtime code
  • t1k-unity-dots-core-ecs — ECS patterns (DOTS context, not MonoBehaviour)