[Unity / C#] 실시간 UI 업데이트

주예성·2025년 6월 12일

📋 목차

  1. 이벤트 시스템
  2. Text 및 Bar 업데이트
  3. 최종 결과
  4. 오늘의 배운 점
  5. 다음 계획

🎈 이벤트 시스템

실시간 변동 데이터를 전달할 때 유용한 시스템으로 수치 변화가 있을 때 자주 사용됩니다.

1. 이벤트 선언

스탯이 변했을 때 알려줄 방송국입니다. PlayerStats를 매개변수로 전달합니다.

// PlayerState.cs

public event System.Action<PlayerStats> OnStatsChanged;

2. 이벤트 발생

지금 스탯이 변했고, 현재 스탯은 '이거'라고 알려주는 방송입니다. 여기서 ?.는 안전장치 입니다.

// PlayerState.cs의 ModifyHealth, ModifySatiety, ModifyHydration에 들어갑니다.

OnStatschanged?.Invoke(stats);

3. 이벤트 작성

EventPlayerState에서 선언하고, 호출하고 싶을 때를 PlayerState의 Modify함수에 작성했습니다. 이 이벤트가 무엇을 할 것인지를 담당할 스크립트는 UIManager이므로 해당 스크립트를 수정해보겠습니다.

// UIManager.cs

[Header("Player")]

private PlayerState playerState;

void Start()
{
	if (player != null)
    {
    	playerState = player.GetComponent<PlayerState>();
        UpdateUI(playerState.stats);
        playerState.OnStatsChanged += UpdateUI;
    }
}

private void UpdateUI(PlayerStats stats)
{
	// Text와 Bar를 업데이트 하는 로직
}

✨ Text 및 Bar 업데이트

Text와 Bar를 업데이트 하기 위해서는 대상이 필요합니다.
Bar: 현재 플레이어 정보를 게이지로 표현함. 현재 수치 / 최대 수치 계산으로 fillAmount를 조절함.
Text: 현재 플레이어 정보를 숫자로 표현함. ToString("F0")을 이용하여 소수점이 드러나지 않도록 함.

// UIManager.cs

[Header("Bar")]
public Image healthBar;
public Image satietyBar;
public Image hydrationBar;

[Header("Text")]
public Text healthText;
public Text satietyText;
public Text hydrationText;

private void UpdateUI(PlayerStats stats)
{
    if (healthBar && satietyBar && hydrationBar)
    {
        healthBar.fillAmount = stats.health / GameConstants.MAX_HEALTH;
        satietyBar.fillAmount = stats.satiety / GameConstants.MAX_SATIETY;
        hydrationBar.fillAmount = stats.hydration / GameConstants.MAX_HYDRATION;
    }

    if (healthText && satietyText && hydrationText)
    {
        healthText.text = stats.health.ToString("F0");  
        satietyText.text = stats.satiety.ToString("F0");
        hydrationText.text = stats.hydration.ToString("F0");
    }
}

🎮 최종 결과

1. 포만감과 수분 감소

2. 체력 감소


📚 오늘의 배운 점

  • EventSystem으로 Player StateUIManager연결
  • TextImage 제어

🎯 다음 계획

다음 글에서는:

  1. 임시 아이템 생성 (체력, 포만감, 수분)
  2. 아이템 사용시 스탯 증감
profile
Unreal Engine & Unity 게임 개발자

0개의 댓글