Model-View-Presenter Pattern (MVP) — Design Patterns for Unity #4

Make your code more efficient by useful patterns

OnurKiris
2 min readJun 17, 2022
Photo by James McDonald on Unsplash

Model-View-Presenter Pattern (MVP)

You may heard of more traditional kind of this pattern which is Model-View-Controller. It also has different kinds like Model-View-ViewModel but I will try to explain more suitable one for Unity which is MVP in our case.

MVP diagram from gdev.tv/design-pattern-slides

MVP is basically separates your code into three parts based on use:

  • Model is just responsible for game logic and expose the data that it knows
  • View is responsible for rendering of that UI elements and events which is what Unity already doing for us in its UI canvas (Buttons etc.)
  • Presenter is responsible for input processing and formatting on UI

Lets say we have a level up mechanism in our game and player can increase XP by simply pressing button on the screen. In this case there will be:

  • ‘Level’ script which represents Model in our example
  • UI Canvas which represents View in our example
  • Finally, ‘LevelPresenter’ script which represents Presenter

Follow below steps to how to implement this pattern logic:

1 — Create ‘Level’ script to manage logic for level up mechanism. Basically, your script should look like:

As you can see above, ‘Level’ script is only dealing with the logic, not updating UI or something else. Its telling to LevelPresenter to do that on experience change as OnChange arrow indicates in diagram picture.

2 — Create ‘LevelPresenter’ script for managing input processing and UI formatting. Your script should look like:

As you can see above:

  • Fields about UI elements represents ‘Formatting’ feature
  • Button element which allows player to increase experience by clicking, represents ‘Input processing’ feature.
  • The reference to ‘Level’ represents Update arrow to Model on diagram.
  • Finally updating Text UI element represents Update arrow to View on diagram.

3 — View is basically Canvas which is dealing with rendering UI for the player. When player presses button from the screen to increase XP, OnEvent feature fulfills.

Thanks for reading!

Feel free to reach me out on LinkedIn if you have questions.

See you on next part — Finite State Machine

--

--