In this lesson, you will learn how to decouple your game logic from visual representation by implementing the Model-View-Controller (MVC) pattern to ensure your code remains scalable and modular.
The Core Concept of MVC
As your game grows, keeping input handling, game state, and rendering all inside a single MonoBehaviour leads to "spaghetti code." The MVC pattern solves this by dividing your system into three distinct roles:
- Model: Holds the raw data and business logic (e.g., a
PlayerStatsclass with health variables). It knows nothing about the UI or the scene. - View: Responsible only for display (e.g., updating a
Slideror playing a particle effect). It observes the Model but never changes the game data directly. - Controller: Acts as the bridge. It listens for user input, processes commands, and updates the Model accordingly.
Practical Implementation
Imagine a player health system. Instead of the UI updating the health variable directly, you structure it like this:
// Model: Pure data and logic
public class HealthModel {
public int CurrentHealth { get; private set; }
public event Action<int> OnHealthChanged;
public void TakeDamage(int amount) {
CurrentHealth -= amount;
OnHealthChanged?.Invoke(CurrentHealth);
}
}
// View: Listens to the Model
public class HealthBarView : MonoBehaviour {
[SerializeField] private Slider slider;
public void UpdateUI(int health) {
slider.value = health;
}
}
// Controller: Handles input and links Model to View
public class PlayerController : MonoBehaviour {
private HealthModel model;
private HealthBarView view;
void Start() {
model.OnHealthChanged += view.UpdateUI;
}
void Update() {
if (Input.GetKeyDown(KeyCode.Space)) model.TakeDamage(10);
}
}
Why This Matters
By separating these layers, you can swap out your UI (the View) without touching your core gameplay rules (the Model). If you decide to add a new "Game Over" screen or a different input method, you only need to modify the relevant layer rather than refactoring the entire codebase. This keeps your architecture lean and adheres to the Single Responsibility Principle we’ve covered previously.
Key Takeaway: MVC separates your game’s data, visual presentation, and input handling into independent layers, allowing you to modify one component without causing ripple effects throughout your entire project.