Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Whats the correct design pattern to setup code that links to UI with game data?

Discussion in 'UI Toolkit' started by TheCelt, Jul 18, 2023.

  1. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    721
    For UI toolkit where a lot of the UI links to game data in real time and updates in real time, i find i'm writing a single class that links multiple things to the UI it becomes essentially a master class. It's not clear how to do this in a compositional way like you could with the original UI system and having monobehaviours on the UI elements.

    What is the best design pattern for using UI toolkit linked to game data not just simple menus ? It's really not clear.
     
  2. magnetic_scho

    magnetic_scho

    Joined:
    Feb 2, 2020
    Posts:
    69
  3. TheCelt

    TheCelt

    Joined:
    Feb 27, 2013
    Posts:
    721
    Those script examples don't really explain the design pattern. If you need to use UniRx to go along with it, that kinda suggests there is no clean way to do it without some external library.
     
  4. dlorre

    dlorre

    Joined:
    Apr 12, 2020
    Posts:
    700
    Some kind of binding is being implemented I believe. It works only for editor as of now.
     
  5. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    5,769
    dlorre likes this.
  6. magnetic_scho

    magnetic_scho

    Joined:
    Feb 2, 2020
    Posts:
    69
    It uses the Model View ViewModel design pattern:
    https://en.wikipedia.org/wiki/Model–view–viewmodel
     
  7. Onigiri

    Onigiri

    Joined:
    Aug 10, 2014
    Posts:
    410
  8. magnetic_scho

    magnetic_scho

    Joined:
    Feb 2, 2020
    Posts:
    69
    It wrapped your models and exposes properties of primitive types and/or IObservables:

    Code (CSharp):
    1.  
    2. public class PerkViewModel
    3. {
    4.     private readonly IPerk _perk;
    5.  
    6.     public PerkViewModel(IPerk perk)
    7.     {
    8.         _perk = perk;
    9.     }
    10.  
    11.     public string Name => _perk.Definition.Type.ToNameLocaKey().Localize();
    12.  
    13.     public IObservable<string> Description => _perk.OnChangedAsObservable()
    14.         .Select<IPerk, string>(p => p.LocalizeEffect());
    15. }
    16.  
     
    Onigiri likes this.