안녕하세요

프로그램 과정에서 막혔던 문제들에 대한 해결책 정리


페이지 목록

레이블이 MVC 모델 관리인 게시물을 표시합니다. 모든 게시물 표시
레이블이 MVC 모델 관리인 게시물을 표시합니다. 모든 게시물 표시

2024년 12월 23일 월요일

[Unity][Copilot][유니티][코파일럿] MVC 모델을 이용하여 개발을 해보자

  코파일럿을 타고 들어가다 보니 MVC 모델로 만들면 좋다고 한다.

 Model-View-Controller로 만든다는 것이다.

 Model은 데이터 관리를 하는 모델을 담당하고

 View는 UI에 그려주는 일을 담당한다.

 Controller에서는 Model과 View를 이어주는 역할을 한다.


 이렇게 만들면 유지 보수와 재사용성을 높일 수 있다고 한다. 정말 그런지 맛을 한번 보자.


--Model--

public class PlayerModel

{

    public int Health { get; set; }

    public int Score { get; set; }


    public PlayerModel(int health, int score)

    {

        Health = health;

        Score = score;

    }


    public void TakeDamage(int damage)

    {

        Health -= damage;

        if (Health < 0)

        {

            Health = 0;

        }

    }


    public void AddScore(int points)

    {

        Score += points;

    }

}


--View --

using UnityEngine;

using UnityEngine.UI;


public class PlayerView : MonoBehaviour

{

    public Text healthText;

    public Text scoreText;


    public void UpdateHealth(int health)

    {

        healthText.text = "Health: " + health;

    }


    public void UpdateScore(int score)

    {

        scoreText.text = "Score: " + score;

    }

}


--Controller--
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    private PlayerModel playerModel;
    private PlayerView playerView;

    void Start()
    {
        playerModel = new PlayerModel(100, 0);
        playerView = FindObjectOfType<PlayerView>();

        // 초기 상태 업데이트
        playerView.UpdateHealth(playerModel.Health);
        playerView.UpdateScore(playerModel.Score);
    }

    void Update()
    {
        // 예: 스페이스바를 눌러 점수 추가
        if (Input.GetKeyDown(KeyCode.Space))
        {
            playerModel.AddScore(10);
            playerView.UpdateScore(playerModel.Score);
        }

        // 예: 데미지 처리
        if (Input.GetKeyDown(KeyCode.D))
        {
            playerModel.TakeDamage(10);
            playerView.UpdateHealth(playerModel.Health);
        }
    }
}


** 본 문은 Microsoft Copilot의 도움으로 작성되었습니다.