Unity••16 min•237 views••
Kiến Trúc UI Trong Unity: MVC, MVP & MVVM
Minh Khoa
Tác giả
UI Architecture trong Unity: MVC, MVP, MVVM
Mục tiêu: Hiểu rõ vì sao UI và Logic thường bị "rối mì" trong Unity, nắm vững ba kiến trúc chuyên nghiệp (MVC, MVP, MVVM) và biết cách áp dụng phù hợp cho từng tình huống thực tế.

📌 MỞ ĐẦU — NHẬN DIỆN VẤN ĐỀ THỰC TẾ
Ví dụ Anti-Pattern
// NewStationUI.cs — UI class
private void RefreshUI()
{
bool canAfford = GameController.Instance != null
&& GameController.Instance.CanAfford(cost);
unlockButton.interactable = canAfford;
}
private void OnClickUnlock()
{
if (GameController.Instance.SpendMoney(_currentData.UnlockCost))
{
_currentData?.OnConfirm?.Invoke();
Hide();
}
}
// GamePlayScreen.cs — UI class
public void UpdateUpgradeIconState()
{
var upgrades = DatabaseManager.Instance?.InitConfig?.Upgrades;
if (upgrades != null && GameController.Instance != null)
{
foreach (var data in upgrades)
{
if (!UpgradeState.IsPurchased(data.ID)
&& GameController.Instance.CanAfford(data.Price))
{
canAffordAny = true;
break;
}
}
}
}
Vấn đề
- UI biết quá nhiều về hệ thống.
- Logic bị phân tán.
- Khó test.
- Khó maintain.
- Designer sửa UI có thể làm hỏng logic.
🔑 PHẦN 1 — SEPARATION OF CONCERNS
Model
- Quản lý dữ liệu.
- Chứa business logic.
- Không biết UI tồn tại.
View
- Chỉ hiển thị.
- Nhận input từ người dùng.
- Không chứa business logic.
Controller / Presenter / ViewModel
- Kết nối Model và View.
- Điều phối luồng dữ liệu.
- Không chứa UI code chi tiết.
🔷 PHẦN 2 — MVC
Data Flow
User Input
↓
View
↓
Controller
↓
Model
↓
Notify
↓
View
Ưu điểm
- Đơn giản.
- Ít boilerplate.
- Dễ học.