(유니티)MVC

티원·2025년 11월 10일

디자인패턴

목록 보기
8/16

MVC

MVP 코드
model, View, Controller 로 구성
MVC보다는 익숙해지면 MVP를 쓰는 것이 좋다고 한다.
이유는 MVP 글의 차이점 참조
MVC는 Model과 view가 서로를 알아도 된다. MVP는 알면안됨.

코드

  1. Model
public class PlayerModel
{
    //로직 코드
    private int health = 100;
    public int Health => health;
    public event Action<int> OnHealthChanged;

    public void TakeDamage(int amount)
    {
        health -= amount;
        OnHealthChanged?.Invoke(health);
    }
}
  1. View
public class PlayerView : MonoBehaviour
{
    //UI 코드
    [SerializeField] private TextMeshProUGUI healthText;
    public void UpdateHealthUI(int currentHealth)
    {
        healthText.text = $"HP : {currentHealth}";
    }
}
  1. Controller
public class PlayerController : MonoBehaviour
{
    //View랑 Model을 이어서 처리한다
    [SerializeField] private PlayerView playerView;
    [SerializeField] PlayerModel model;
    //데미지 받게할 처리가 필요해서 InputAction
    InputAction damageAction;
    private void Awake()
    {
        damageAction = InputSystem.actions.FindAction("Attack");
    }
    private void Start()
    {
        model.OnHealthChanged += playerView.UpdateHealthUI;
        playerView.UpdateHealthUI(model.Health);
    }
    private void OnEnable()
    {
        damageAction.performed += OnDamageTriggered;
    }
    private void OnDisable()
    {
        damageAction.performed -= OnDamageTriggered;
    }

    private void OnDamageTriggered(InputAction.CallbackContext ctx)
    {
        model.TakeDamage(10);
    }
}

코딩 순서 추천

Model코드를 작성해서 데이터와 로직 짜고, View코드로 UI로 어떻게 표시할 것인지 대략적으로 생각
마지막으로 Controller코드로 model과 View를 이어서 사용

MVC 이론

Model, View, Controller
Model: 데이터와 로직 //플레이어 체력,경험치,점수 등등 데이터
view: 표시 //UI
Controller: 입력 및 로직 연결 //키 입력, 버튼 클릭을 받아서 모델을 변경

뷰: 보여주는 일
컨트롤러: 입력받아서 모델변경
모델: 데이터 저장, 관리

코드 유지보수가 좋아짐. UI교체나 로직 변경이 모두 독립적으로 가능
프로그램 구조를 역할별로 분리하여서 관리
쉽게만든 아키텍쳐/패턴

언제 MVC를 고려해야하는가?

  • UI, 입력, 데이터가 뒤섞여서 코드 복잡할 때
  • 팀플에서, "UI담당자", "입력 등 로직 담당자" 따로 둘 때
  • 게임 내 정보(체력, 골드, 인벤토리 등) UI 여러곳에서 표시가 되야 할 때

0개의 댓글