Unity-MVVM
In Unity3D game development, the MVVM framework can be used very well. The following is a description of how the Unity project is layered.
View
The view layer generally includes windows, view scripts, UI controls, animation scripts, view resources, and other view layer auxiliary tools, such as view locators. Specifically, you can abstract and plan according to your own project situation.
Window/UIView
Window and view scripts control the life cycle of all views, such as the creation and destruction of subviews and subwindows should be written in this layer of code. If the logic of opening and closing the interface is triggered by functions in the ViewModel layer, then use IDialogService or exchange requests to send events to the view script for execution.
UI controls (UGUI controls or custom controls)
UI control layer, custom UI controls should be written in this layer, and it is strongly recommended that UI functions be controlled, such as lists, dialog boxes, progress bars, Grid, Menu, etc. should be written as universal UI controls.
Animation
UI animation layer, for example, you can use DoTween to write various window animations or interface animations, and directly hang them on the UI GameObject. You can refer to my example to write. If it is a window animation, please inherit my UIAnimation or use GenericUIAnimation to implement.
View locator(IUIViewLocator)
View locator, which uses the view locator to load view templates from Resources or from AssetBundle. Of course, you can refer to my UI view locator to write your own 3D view locator.
Interation Action
Interaction behavior. This is an abstraction for window and view creation code reuse. It encapsulates some frequently used interface creation code as interaction behavior.
ViewModel
The view model layer contains all the view models and subview models. Generally, the view models of Window and View are paired one by one. A window must have a view model, and the subviews under a window should generally have corresponding subviews. model. However, pure view object-encapsulated subview models, such as UserInfoVM, can be shared by multiple views, and when the UserInfoVM property changes, multiple interfaces bound to it will change at the same time.
View model locator (IViewModelLocator)
View model locator, which is used to manage the shared sub-view model, or to save the window view model (such as the window is closed but the view model is not destroyed, the next time you open the window, you can use it to restore the window state). This layer is not necessary, it can be omitted or replaced with another solution.
Application layer (Service)
The application layer is mainly used to express user use cases and coordinate the behavior between objects in different domains. If the design concept of the DDD congestion model is adopted, it is only a very thin layer. It exists as a bridge between the presentation layer and the domain layer, and provides services for the presentation layer through application services. If the design idea of the traditional anemia model is adopted, it should include all the business logic processing. I don’t know much about DDD programming among the students who use the framework, so here I recommend the design idea of the traditional anemia model to develop the game. In my project example, it corresponds to the Services layer.
For example, a game project may include character services, backpack services, equipment services, skill services, chat services, item services, and so on. These services are used to manage character information, items in the backpack, user equipment, user learned skills, chat information , Chat room information, and more. The service caches this information and ensures that they are synchronized with the server through Load or server push. When there is a message update, an event is triggered to notify the view model layer to update. For example, various red dots on the main interface (the state that prompts a new message) can be designed through the events of each service and the red dot status on the view model.
Domain Model
The domain layer is responsible for the expression and processing of business logic and is the core of the entire business. If you program according to DDD, the domain layer generally includes concepts such as entities, value objects, domain services, aggregation, aggregation roots, storage, and factories, because the concepts involved are numerous and persistence needs to be compatible with the CQRS + ES model, and there are considerable thresholds to master. So if you are not very familiar with DDD, I don’t recommend designing your code completely according to the DDD programming idea, but adopt the idea of the anemia model. Below, I will only make a simple idea of some concepts to be used in the anemia model. Introduction.
Entity
Entities must have unique identifiers, such as objects such as account numbers, characters, skills, equipment, and props in the game, which are all entity objects.
Value Object
The value object is used to describe an object in a certain aspect of the domain that does not have a conceptual identifier. The value object is different from the entity. It has no unique identifier and its attributes are immutable, such as some game table information.
Repository
The warehousing layer is responsible for functions such as adding, deleting, modifying, and checking the entity objects. Through the warehousing layer, you can read data or persist data. The data can be saved in local Json, xml, SQLite, or on the server through the network.
Infrastructure
The base layer contains the framework, database access components, network components, Log components, Protobuf components, public helper classes and methods.
I’m the author of LoxodonFramework, here are some examples to show the relationship between View and ViewModel.
View:
using Loxodon.Framework.Binding;
using Loxodon.Framework.Binding.Builder;
using Loxodon.Framework.Interactivity;
using Loxodon.Framework.Views;
using Loxodon.Log;
using UnityEngine.UI;
namespace Loxodon.Framework.Examples
{
public class LoginWindow : Window
{
//private static readonly ILog log = LogManager.GetLogger(typeof(LoginWindow));
public InputField username;
public InputField password;
public Text usernameErrorPrompt;
public Text passwordErrorPrompt;
public Button confirmButton;
public Button cancelButton;
protected override void OnCreate(IBundle bundle)
{
BindingSet<LoginWindow, LoginViewModel> bindingSet = this.CreateBindingSet<LoginWindow, LoginViewModel>();
bindingSet.Bind().For(v => v.OnInteractionFinished).To(vm => vm.InteractionFinished);
bindingSet.Bind().For(v => v.OnToastShow).To(vm => vm.ToastRequest);
bindingSet.Bind(this.username).For(v => v.text, v => v.onEndEdit).To(vm => vm.Username).TwoWay();
bindingSet.Bind(this.usernameErrorPrompt).For(v => v.text).To(vm => vm.Errors["username"]).OneWay();
bindingSet.Bind(this.password).For(v => v.text, v => v.onEndEdit).To(vm => vm.Password).TwoWay();
bindingSet.Bind(this.passwordErrorPrompt).For(v => v.text).To(vm => vm.Errors["password"]).OneWay();
bindingSet.Bind(this.confirmButton).For(v => v.onClick).To(vm => vm.LoginCommand);
bindingSet.Bind(this.cancelButton).For(v => v.onClick).To(vm => vm.CancelCommand);
bindingSet.Build();
}
public virtual void OnInteractionFinished(object sender, InteractionEventArgs args)
{
this.Dismiss();
}
public virtual void OnToastShow(object sender, InteractionEventArgs args)
{
Notification notification = args.Context as Notification;
if (notification == null)
return;
Toast.Show(this, notification.Message, 2f);
}
}
}
ViewModel:
```csharp
**using System;
using System.Text.RegularExpressions;
using Loxodon.Log;
using Loxodon.Framework.Contexts;
using Loxodon.Framework.Prefs;
using Loxodon.Framework.Asynchronous;
using Loxodon.Framework.Commands;
using Loxodon.Framework.ViewModels;
using Loxodon.Framework.Localizations;
using Loxodon.Framework.Observables;
using Loxodon.Framework.Interactivity;
namespace Loxodon.Framework.Examples
{
public class LoginViewModel : ViewModelBase
{
private static readonly ILog log = LogManager.GetLogger(typeof(ViewModelBase));
private const string LAST_USERNAME_KEY = "LAST_USERNAME";
private ObservableDictionary<string, string> errors = new ObservableDictionary<string, string>();
private string username;
private string password;
private SimpleCommand loginCommand;
private SimpleCommand cancelCommand;
private Account account;
private Preferences globalPreferences;
private IAccountService accountService;
private Localization localization;
private InteractionRequest interactionFinished;
private InteractionRequest<Notification> toastRequest;
public LoginViewModel(IAccountService accountService, Localization localization, Preferences globalPreferences)
{
this.localization = localization;
this.accountService = accountService;
this.globalPreferences = globalPreferences;
this.interactionFinished = new InteractionRequest(this);
this.toastRequest = new InteractionRequest<Notification>(this);
if (this.username == null)
{
this.username = globalPreferences.GetString(LAST_USERNAME_KEY, "");
}
this.loginCommand = new SimpleCommand(this.Login);
this.cancelCommand = new SimpleCommand(() =>
{
this.interactionFinished.Raise();/* Request to close the login window */
});
}
public IInteractionRequest InteractionFinished
{
get { return this.interactionFinished; }
}
public IInteractionRequest ToastRequest
{
get { return this.toastRequest; }
}
public ObservableDictionary<string, string> Errors { get { return this.errors; } }
public string Username
{
get { return this.username; }
set
{
if (this.Set<string>(ref this.username, value))
{
this.ValidateUsername();
}
}
}
public string Password
{
get { return this.password; }
set
{
if (this.Set<string>(ref this.password, value))
{
this.ValidatePassword();
}
}
}
private bool ValidateUsername()
{
if (string.IsNullOrEmpty(this.username) || !Regex.IsMatch(this.username, "^[a-zA-Z0-9_-]{4,12}$"))
{
this.errors["username"] = localization.GetText("login.validation.username.error", "Please enter a valid username.");
return false;
}
else
{
this.errors.Remove("username");
return true;
}
}
private bool ValidatePassword()
{
if (string.IsNullOrEmpty(this.password) || !Regex.IsMatch(this.password, "^[a-zA-Z0-9_-]{4,12}$"))
{
this.errors["password"] = localization.GetText("login.validation.password.error", "Please enter a valid password.");
return false;
}
else
{
this.errors.Remove("password");
return true;
}
}
public ICommand LoginCommand
{
get { return this.loginCommand; }
}
public ICommand CancelCommand
{
get { return this.cancelCommand; }
}
public Account Account
{
get { return this.account; }
}
public async void Login()
{
try
{
if (log.IsDebugEnabled)
log.DebugFormat("login start. username:{0} password:{1}", this.username, this.password);
this.account = null;
this.loginCommand.Enabled = false;/*by databinding, auto set button.interactable = false. */
if (!(this.ValidateUsername() && this.ValidatePassword()))
return;
IAsyncResult<Account> result = this.accountService.Login(this.username, this.password);
Account account = await result;
if (result.Exception != null)
{
if (log.IsErrorEnabled)
log.ErrorFormat("Exception:{0}", result.Exception);
var tipContent = this.localization.GetText("login.exception.tip", "Login exception.");
this.toastRequest.Raise(new Notification(tipContent));/* show toast */
return;
}
if (account != null)
{
/* login success */
globalPreferences.SetString(LAST_USERNAME_KEY, this.username);
globalPreferences.Save();
this.account = account;
this.interactionFinished.Raise();/* Interaction completed, request to close the login window */
}
else
{
/* Login failure */
var tipContent = this.localization.GetText("login.failure.tip", "Login failure.");
this.toastRequest.Raise(new Notification(tipContent));/* show toast */
}
}
finally
{
this.loginCommand.Enabled = true;/*by databinding, auto set button.interactable = true. */
}
}
public IAsyncResult<Account> GetAccount()
{
return this.accountService.GetAccount(this.Username);
}
}
}**
** __**Domains:**__ __**
csharp__
**using System;
using Loxodon.Framework.Observables;
namespace Loxodon.Framework.Examples
{
public class Account : ObservableObject
{
private string username;
private string password;
private DateTime created;
public string Username {
get{ return this.username; }
set{ this.Set<string> (ref this.username, value); }
}
public string Password {
get{ return this.password; }
set{ this.Set<string> (ref this.password, value); }
}
public DateTime Created {
get{ return this.created; }
set{ this.Set<DateTime> (ref this.created, value); }
}
}
}
__```**__