

Trade Market
2D Action RPG | Unity | C#
A zone-based trading adventure where players defeat enemies and trade items with NPCs to progress. Built focusing on clean architecture patterns and persistent state management across multiple scenes.
Tech Stack: Unity 2D | C# | ScriptableObjects | New Input System | State Machines
Development Approach
I structured the project using MVC + Service Layer to avoid the common Unity pitfall of everything being a MonoBehaviour with crossed dependencies. The GameService acts as a central hub - when the player trades with an NPC, the call goes GameService → NPCManager → NPCRepository → specific NPCController. This made debugging significantly easier since I could isolate which layer was failing.
I separated data from logic using ScriptableObjects for all entity stats (player health, enemy fire rates, NPC dialogue). This meant balancing didn't require code changes - I could adjust enemy damage in the inspector and test immediately. Components communicate through events (delegates) to stay decoupled - when health changes, the Model broadcasts an event that UI widgets listen to without knowing about each other.

Key Technical System
-
Object Pooling for Bullets
-
My initial approach was spawning/destroying bullet GameObjects on every shot, which caused GC spikes during combat (10-15ms stutters). I implemented a generic object pool that pre-instantiates bullets and reuses them.
-
The pool works in three layers:
-
BulletController: Handles firing logic and lifetime tracking
-
BulletView: MonoBehaviour that responds to Rigidbody2D collisions via OnTriggerEnter2D
-
BulletService: Manages the pool and updates all active bullets each frame
-
-
When a bullet expires (lifetime > 2s), the controller calls DeactivateBullet() which sets the view inactive and returns it to the pool. The key insight was making BulletView abstract with a HandleTrigger() method - PlayerBullet and EnemyBullet extend it with their specific damage logic without duplicating collision code.
-
The pool uses a List<PooledItem<T>> where each item tracks isUsed. When requesting a bullet, it searches for an unused one matching the type (PlayerBullet vs EnemyBullet). If none exist, it instantiates a new one. This reduced per-frame allocations from ~500KB to nearly zero during firefights.
-
-
ScriptableObject-Based Save System
-
I needed persistent data across scenes but wanted to avoid PlayerPrefs for flexibility. I created PlayerDataScriptableObject that lives in the project and acts as runtime save storage. The PlayerSaveManager reads/writes to this SO instead of serializing to disk.
-
The challenge was distinguishing first-time play from returning sessions. I added a hasInitializedThisSession bool that gets set true after the first save. On game start:
-
When the player trades items, the PlayerModel.SetItem() method immediately updates playerData.currentItem in the SO. This happens synchronously, so if Unity crashes mid-session, the SO retains the last state. Scene transitions call SavePlayerState() which batch-updates position, inventory state, and completed zones.
-
The SO approach also simplified testing - I could manually reset the SO in the inspector between playthroughs instead of clearing PlayerPrefs keys. For production, this would be swapped to JSON serialization, but the architecture stays identical since everything goes through the SaveManager interface.
-
-
-
When the player trades items, the PlayerModel.SetItem() method immediately updates playerData.currentItem in the SO. This happens synchronously, so if Unity crashes mid-session, the SO retains the last state. Scene transitions call SavePlayerState() which batch-updates position, inventory state, and completed zones.
-
The SO approach also simplified testing - I could manually reset the SO in the inspector between playthroughs instead of clearing PlayerPrefs keys. For production, this would be swapped to JSON serialization, but the architecture stays identical since everything goes through the SaveManager interface.
-
-
NPC Trading State Machine
-
NPCs needed multi-step dialogue (greeting → trade offer → completion) without external state tracking. I implemented this using controller-level flags that reset spatially.
-
The NPCController has two bools: hasGreeted and hasShownTradeOffer. When the player presses E:
-
First interaction: Shows greeting dialogue, sets hasGreeted = true
-
Second interaction: Shows trade offer with item names, sets hasShownTradeOffer = true
-
Third+ interaction: Checks if player has the desired item
-
If yes → Shows trade confirmation UI via GameService.uiService
-
If no → Shows rejection dialogue
-
-
-
The key design choice was resetting these flags in OnTriggerExit2D. When the player walks away, both flags reset to false but NPCModel.HasTraded (the permanent state) stays true. This creates a natural conversation flow - NPCs "forget" the incomplete conversation but remember if you already traded.
-
For the trade confirmation UI, I had to solve a tricky issue: the player needed to be immobile during the trade panel. I added PlayerModel.IsInTradeMode which gets set true when the panel appears. The PlayerController.SetMovement() checks this flag and early-returns if true, preventing WASD input from moving the character. When the trade completes or cancels, SetTradeMode(false) re-enables movement.
-

-
Bullet Directional Firing System
-
Players fire bullets in their last movement direction using a firePoint Transform that rotates to face that direction. In PlayerView.UpdateFirePoint(), I calculate the angle from the lastMovement vector:
-
-
-
Initially, bullets fired backward when moving left because the sprite flipped but the fire point didn't. I fixed this by adjusting the fire point's local Y scale based on the X direction:
-
-
-
This mirrors the fire point when moving left, keeping bullets aimed correctly without duplicating fire logic for each direction.
-
Technical Challenges
-
Animation Synchronization: Initially, player firing and enemy spawning sounds played even when the entities were off-screen or inactive. I added state checks (if (!IsActive) return;) before every sound call and tied sound playback to animation events in some cases, ensuring audio only plays for visible, active entities.
-
Circular Dependencies: Early on, NPCController directly referenced PlayerController to check inventory. This created a compile error when PlayerController tried to access NPCController for trades. I solved this by routing everything through GameService - NPCs call GameService.Instance.playerService.PlayerModel.CurrentItem and players call GameService.Instance.ExecuteTradeWithNPC(). The service acts as a mediator, breaking the circular reference.
-
State Machine Complexity: The PlayerStateMachine originally checked IsDead in every state's Update(). This was repetitive across Idle/Walk states. I refactored to check death in the base Update() call before delegating to the current state, centralizing the transition logic in one place.
What I Learned
Component-based architecture made debugging significantly easier - when firing broke, I only checked BulletController/View/Service instead of monolithic player code. ScriptableObjects for data meant designers (or me during testing) could balance without code recompilation. I learned to use events/delegates for cross-system communication to keep systems loosely coupled - the UI doesn't need to know about PlayerModel internals, it just subscribes to OnInventoryToggled. Writing generic systems like GenericObjectPool<T> took more upfront time but saved effort when I later needed pooling for enemy effects and UI popups.