In this lesson, you will learn how to detect the "God Object" anti-pattern by analyzing tight coupling and low cohesion in your scripts.
As your projects grow, a script that once handled simple character movement often mutates into a massive, multi-purpose monolith. These "God Objects" act as central hubs for everything—input handling, animation state, sound playback, and inventory management. While convenient, they are a primary source of technical debt.
Recognizing the Smells
The most reliable way to spot a God Object is to examine its dependencies and responsibilities.
- Low Cohesion: If your class requires
usingstatements for entirely unrelated systems—like bothUnityEngine.UIandUnityEngine.AI—it is likely trying to do too much. A class should ideally have a single responsibility. - Tight Coupling: If you find yourself needing to pass references to ten different managers into a single script just to get it to function, you have created a "dependency spiderweb."
- Cyclomatic Complexity: If a single file contains hundreds of lines of code with deeply nested
if/elseorswitchstatements controlling different game states, it is a sign that your logic needs to be broken apart into modular components or strategy patterns.
A Typical Smelly Class
Imagine a PlayerController script that looks like this:
public class PlayerController : MonoBehaviour {
// Too many responsibilities!
public void Update() {
HandleMovement(); // Movement logic
UpdateUI(); // UI interaction
SaveProgress(); // Persistence logic
CheckInventory(); // Data management
}
}
This script is highly fragile. A change to the UI logic might inadvertently break the save system because they are forced to share the same execution space. To refactor, look for groups of variables and methods that only interact with each other. If CheckInventory and its related fields can exist independently, they should be moved to a dedicated InventoryManager or handled via an Event Channel.
By identifying where the logic lacks cohesion, you can target the most volatile parts of your code for extraction into modular components or ScriptableObject-based systems.
Key Takeaway: A script that knows too much and does too much is brittle; look for high dependency counts and unrelated method clusters as your primary indicators for urgent refactoring.