In this lesson, you will learn how to use interface-based programming to break tight dependencies between your game systems, allowing them to interact through shared contracts rather than concrete types.
The Problem: Tight Coupling
In a typical Unity project, you might have a PlayerController that directly references a HealthSystem class. This creates a "tight coupling": if you want to change how health works or swap it for a different system entirely, you have to rewrite parts of your PlayerController. This makes your code rigid and difficult to test.
The Solution: Programming to an Interface
Instead of relying on a concrete class, we define an IHealth interface. This serves as a "contract" that guarantees specific methods exist without dictating how they work.
First, define your interface:
public interface IHealth {
void TakeDamage(float amount);
float CurrentHealth { get; }
}
Now, your PlayerController doesn't need to know if it is talking to a PlayerHealth script or a DummyTarget script; it only needs an IHealth object.
public class PlayerController : MonoBehaviour {
// We only care that this object follows the IHealth contract
public void DamageTarget(IHealth target) {
target.TakeDamage(10f);
}
}
Why This Matters for Architecture
When you use interfaces, your systems become modular. Because the PlayerController is decoupled from the concrete implementation, you can inject a MockHealth object during unit testing or swap in a ShieldSystem that also implements IHealth without changing a single line of code in the controller.
This approach shifts your design thinking: you stop asking "What class is this object?" and start asking "What can this object do?". By focusing on capabilities defined by interfaces, you ensure that your game architecture remains flexible as your project scales, preventing the dreaded "spaghetti code" where every script is interconnected and fragile.
Key Takeaway: By coding to interfaces instead of concrete classes, you create a modular architecture where systems remain independent, testable, and interchangeable.