top of page
Search
yuli0203

MVVM In Unity

Updated: Feb 23, 2023

This article is about how to properly create a reusable, modular and decoupled game component, and organizing its code using the MVVM pattern.


This is the classic MVVM pattern (taken from Wikipiedia).


Before we apply it to Unity I will introduce my approach. There are many ways to apply the same pattern. I adapt the patterns to my development needs, rather than the development to the patterns. In this case, the Monobehavior component present constraints that made me adjust the pattern in a certain way. Also, in my experience I found that most of the prefab components are best designed small and composable.

You can achieve similar goals with using other UI pattern such as MVP, MVC and etc.

View


Our view is the Unity framework, which takes care of our presentation needs.


View Model


View model - The presentation logic, in my opinion, is a definition that fits like a glove to the Monobehavior component (since it has a lifecycle, it has logic by definition). Monobehavior script is our connecting gateway to Unity framework, with the rest of our application. Our data-binding between the View and the ViewModel is by dragging the View components into the appropriate serialized fields (for example we can drag a simple mock gameobject instead of a complex prefab). Monobehaviors are components that are harder to test and isolate, therefore they should contain the minimal and the simplest presentation logic, such as event subscriptions and animations. In order to reuse them properly along with the prefab they sit on, they must not know the rest of the code. They can be known by the rest of the code, and the best way is by an interface.

With this approach when composing prefabs from other prefabs, it is very easy to compose their ViewModels as well by serialized fields in an hierarchical way.


Model - Business logic and Data


Data - This is a component which contains data only. It can be a component from a containing scope (for example a global scope). It can be a Scriptable Object, a Struct or a behavior-less Class.


Logic - A class known as a Manager, Controller, Logic etc... This is the class that contains the logic, and orchestrates the whole component behavior along with the injected Data and ViewModel.


Wrap it up


Lets summarize some benefits of using MVVM in our components: 1. Having the scripts named will help identify their roles easily, and make them searchable.

2. Instantiating and composing prefabs as whole, with their presentational logic.

3. MVVM benefits of decoupling logic and View.


I hope you found it useful, thank you for reading!



Recent Posts

See All

Comments


bottom of page