Unity - 2D 종스크롤 슈팅 : UI 완성하기

TXMAY·2023년 9월 25일
0

Unity 튜토리얼

목록 보기
25/33
post-thumbnail

이번 강좌는 UI에 관한 강좌다.


라이프와 스코어

우선 게임에서 필수적인 라이프와 스코어를 만들어 보겠다.
'Player.cs'에 다음과 같이 코드를 추가한다.

...

public int life;
public int score;
...

그리고 UI - Legacy - Text와 UI - Image를 추가한다.
그런 다음 텍스트에 임시 스코어와 이미지에 라이프 이미지를 추가하고 적절히 배치한다.
그런데 UI가 화면 크기에 비해 너무 크다.
그래서 Canvas - Canvas Scaler에서 UI Scale Mode - Scale With Screen Size로 설정한다.
Scale With Screen Size : 기준 해상도의 UI 크기 유지
그리고 Reference Resolution을 1080x1920으로 설정한다.
UI의 크기가 바뀌었는데 다시 조정한다.
그리고 게임오버 텍스트와 재시작 버튼도 만든다.
버튼 이미지의 경우는 버튼의 크기가 변해도 모양이 바뀌면 안 되기에 Sprite Editor에서 Border를 설정해야 한다.
그리고 게임오버 텍스트와 재시작 버튼은 하나의 오브젝트로 묶는다.

UI 로직

이제 스코어와 라이프, 게임오버에 대한 로직을 만들어 보겠다.
다음과 같이 코드들을 입력한다.

// Enemy.cs
...

public int enemyScore;
...

void OnHit(int dmg)
{
    ...
    
    if (health <= 0)
    {
        Player playerLogic = player.GetComponent<Player>();
        playerLogic.score += enemyScore;
        ...
        
    }
}

// GameManager.cs

...

using UnityEngine.SceneManagement;
using UnityEngine.UI;
...

public Text scoreText;
public Image[] lifeImage;
public GameObject gameOverSet;
...

void Update()
{
   	...
   
    Player playerLogic = player.GetComponent<Player>();
    scoreText.text = string.Format("{0:n0}", playerLogic.score);
}
...

public void UpdateLifeIcon(int life)
{
    for (int index = 0; index < 3; index++)
    {
        lifeImage[index].color = new Color(1, 1, 1, 0);
    }
    for (int index = 0; index < life; index++)
    {
        lifeImage[index].color = new Color(1, 1, 1, 1);
    }
}
...

public void GameOver()
{
    gameOverSet.SetActive(true);
}

public void GameRetry()
{
    SceneManager.LoadScene(0);
}

// Player.cs

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Border")
    {
        ...
        
    }
    else if (collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "EnemyBullet")
    {
        life--;
        manager.UpdateLifeIcon(life);

        if (life == 0)
        {
            manager.GameOver();
        }
        else
        {
            manager.RespawnPlayer();
        }
        gameObject.SetActive(false);
        Destroy(collision.gameObject);
    }
}
  • string.Format(format, text) : 지정된 양식으로 문자열을 변환해 주는 함수
  • {0:n0} : 세 자리마다 쉼표로 나눠주는 숫자 양식

코드 작성 후 public 변수들의 값을 설정한다.

예외 처리

중복 피격이 발생하는 것을 해결해 보겠다.
다음과 같이 코드를 추가하고, 수정한다.

// Player.cs
...

void OnTriggerEnter2D(Collider2D collision)
{
    if (collision.gameObject.tag == "Border")
    {
    	...
    
    }
    else if (collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "EnemyBullet")
    {
        if (isHit)
        {
            return;
        }
        isHit = true;
        ...
        
    }
}
...

// GameManager.cs

...

void RespawnPlayerExe()
{
    ...
    
    Player playerLogic = player.GetComponent<Player>();
    playerLogic.isHit = false;
}
...

영상에선 코드들을 여러 번 왔다 갔다 해서 정리할 때 약간 힘들었다.

profile
게임 개발 공부하는 고양이

0개의 댓글