Model-view-controller architecture in Unity

This is going to be a more technical series of posts. I’m going to look at what’s going on under the hood in Delugional, and some of the approaches I took to keep the code manageable.

DelugionalOutside the world of games, the longstanding best practice for building a user interface is the ‘Model View Controller’ or ‘MVC’ pattern. This pattern has spawned many variants, but the basic principle remains the same. You have a ‘model’ layer, the raw information that your application is concerned with. (Eg, this puzzle has water here and some huts here, and this many hexes, and so on.) You have a ‘view’ layer, which is responsible for showing stuff to the user, and accepting input. And finally you have a ‘glue’ layer which is responsible for passing information between the model and the view. The golden rule is that the model knows nothing about the view layer, and the view layer knows nothing about the model. The ‘glue’, implemented in various ways and known as a ‘Controller’ or a ‘Presenter’ or a ‘View Model’, exists to allow and enforce this separation.

The advantage of this approach is simple and profound: you can make changes to your model without changing your view layer, and vice versa. This isn’t such a big deal in the early stages of development, but it saves you a huge amount of pain on a large project.

Does this pattern transfer to game development – or, specifically, to Unity3D development? I admit it must be tricky to apply to, say, a 3d shooter, where the ‘model’ (eg, the game physics) and the ‘view’ (eg, Unity’s rendering) are closely intertwined at an engine level. But for something like Delugional – a puzzle game with a turn-based mechanic – it’s eminently achievable. I’ll explain how I did it. Continue reading “Model-view-controller architecture in Unity”