Model
- 여기에는 데이터와 이 데이터를 관리하는 규칙이 포함
- 게임의 현재 상태, 게임 속성, 데이터에 대한 로직 (캐릭터 레벨업, 체력, 점수 등)
- Model은 View에 대한 정보가 없음
using System;
using UnityEngine;
public class Health : MonoBehaviour
{
public event Action HealthChanged;
private const int minHealth = 0;
private const int maxHealth = 100;
private int currentHealth;
public int CurrentHealth { get => currentHealth; set => currentHealth = value; }
public int MinHealth => minHealth;
public int MaxHealth => maxHealth;
public void Increment(int amount)
{
currentHealth += amount;
currentHealth = Mathf.Clamp(currentHealth, minHealth, maxHealth);
UpdateHealth();
}
public void Decrement(int amount)
{
currentHealth -= amount;
currentHealth = Mathf.Clamp(currentHealth, minHealth, maxHealth);
UpdateHealth();
}
public void Restore()
{
currentHealth = maxHealth;
UpdateHealth();
}
public void UpdateHealth()
{
HealthChanged?.Invoke();
}
}
Presenter
- Model과 View 사이에서 중재
- View에서 사용자 입력 이벤트를 처리
- 게임의 조건이 변경되면 Model을 업데이트하고, View를 업데이트
using UnityEngine;
using UnityEngine.UI;
public class HealthPresenter : MonoBehaviour
{
[Header("Model")]
[SerializeField] private Health health;
[Header("View")]
[SerializeField] private Slider healthSlider;
[SerializeField] private Text healthText;
private void Start()
{
if (health != null)
{
health.HealthChanged += Health_HealthChanged;
}
Reset();
}
private void OnDestroy()
{
if (health != null)
{
health.HealthChanged -= Health_HealthChanged;
}
}
public void Damage(int amount)
{
health?.Decrement(amount);
}
public void Heal(int amount)
{
health?.Increment(amount);
}
public void Reset()
{
health?.Restore();
}
public void UpdateView()
{
if (health == null)
return;
if (healthSlider != null && health.MaxHealth != 0)
{
healthSlider.value = ((float)health.CurrentHealth / (float)health.MaxHealth);
}
if (healthText != null)
{
healthText.text = health.CurrentHealth.ToString();
}
}
public void Health_HealthChanged()
{
UpdateView();
}
}
View
- 사용자에게 데이터를 표시하는 애플리케이션의 UI
- 사용자 상호작용(예: 버튼클릭)을 Presenter로 전송
- MVP 패턴의 View는 Mdeol과 직접 상호작용하지 않음
- UI 로직에 대한 별도의 스크립트가 있을 수 있지만, 게임의 비즈니스 로직을 처리하지 않음