기존에 작성한 결과 창 Text 변경하는 코드가 객체 지향의 원칙를 어기고 비 효율적인 방법이라 생각이 들어 코드 리팩토링을 진행했다.
기존의 방식은 GameManager나 다른 스크립트에서 직접 Text 오브젝트를 붙혀서 해당 Text를 변경했다.
예시
[SerializeField] private Text resultText;
private void text()
{
resultText.text = "안녕하세요";
}
결과 창 UI를 관리하는 **ResultUI.cs
**를 생성하고 해당 스크립트에서 결과 창의 Text 오브젝트들의 Text를 변경하도록 코드를 작성했다.
그리고 게임의 확장성을 생각해서 싱글톤으로 선언 된 GameManager.cs
스크립트에서 **ResultUI.cs
**를 저장하고 get 프로퍼티로 **ResultUI.cs
**를 받아 올 수 있도록 했다.
using UnityEngine;
using UnityEngine.UI;
// 텍스트의 타입을 나타내는 열거형
public enum ResultTextType {Title, Match, Score}
public class ResultUI : MonoBehaviour // 결과창 Text를 변경하는 스크립트
{
[SerializeField] private Text[] resultTexts;
[SerializeField] private GameObject result_UI;
// 결과창의 텍스트를 변경하는 함수
public void TextChange(ResultTextType type, string text)
{
resultTexts[(int)type].text = text;
}
// result UI On/Off
public void UI_OnOff(bool isOn)
{
result_UI.SetActive(isOn);
}
}
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public static GameManager instance ;
[Header("# Component")]
[SerializeField] private ResultUI resultUI; // 매칭 시도 횟수 텍스트
public ResultUI ResultUI { get => resultUI; }
[HideInInspector]public int matchingCount; // 매칭 시도 횟수를 저장하는 변수
/* 변수 선언 */
private void Awake()
{
/* 내용 */
}
private void Start()
{
/* 내용 */
}
void Update()
{
/* 내용 */
}
private void GameEnd()
{
// 2024.04.19
AudioManager.instance.StopBGM();
if (isClear)
{
audioSource.PlayOneShot(clearBGM);
}
else
{
audioSource.PlayOneShot(overBGM);
}
// 매칭 시도 횟수 text 오브젝트에 저장S
// resultText.text = $"매칭 시도 : <color=red>{matchingCount}</color>번";
// 24.4.19 승도 => 코드 리팩토링
**string format = $"매칭 시도 : <color=red>{matchingCount}</color>번";
ResultUI .TextChange(ResultTextType.Match, format);**
isPlay = true;
Time.timeScale = 0f;
ResultUI .UI_OnOff(true);
}
public void Matched()
{
/* 내용 */
}
}
using UnityEngine;
// 점수 계산 스크립트
public class Score : MonoBehaviour //2024.04.18
{
[SerializeField] private ResultUI resultUI;
private GameManager gm;
private void Start()
{
gm = GameManager.instance;
}
public void UpdateScoreText()
{
float timePercentage = gm.timer / gm.maxTime[(int)DifficultyManager.instance.difficulty] * 100f;
int score = CalculateScore(timePercentage);
**gm.ResultUI.TextChange(ResultTextType.Score, $"<color=red>{score}</color> 점");**
}
private int CalculateScore(float timePercentage)
{
/* 내용 */
}
}