Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

인텔리킴의 Unity Studying & Game Analysis

28. 유니티 2D 종스크롤 슈팅 - UI 작성 본문

게임 개발 일지/유니티 엔진 공부

28. 유니티 2D 종스크롤 슈팅 - UI 작성

인텔리킴 2024. 5. 29. 21:00

목숨과 점수 UI 배치

먼저 플레이어 로직에 목숨, 점수 로직 추가

해상도 값 설정

* Scale With Screen Size : 기존 해상도의 UI 크기 유지

* Canvas Scaler 기준 해상도 값 설정

 

 

UI 세팅

 

게임오버는 텍스트 재시작 버튼은 버튼으로

 

버튼 UI는 Border를 통해 타일 설정

Border 설정

 

빈 오브젝트에 삽입

빈 오브젝트에 UI 삽입해서 정리

 

UI 스크립트

점수는 적을 처치할 때 얻기 때문에 Enemy 스크립트에서 계산

 

void onHit(int dmg)
{
    health -= dmg;
    //평소 스프라이트는 0, 피격시 스프라이트는 1
    spriteRenderer.sprite = sprites[1];
    //데미지 들어오고 일정 시간 후 원래대로 스프라이트 돌아오게 함
    Invoke("ReturnSprite", 0.1f);
    if (health <= 0) {
    //점수 계산
        Player playerLogic = player.GetComponent<Player>();
        playerLogic.score += enemyScore;
        Destroy(gameObject);
    }
}

적이 죽어서 Destroy됨과 동시에 점수 계산

 

public TextMeshProUGUI score;
public Image[] lifeImage;
public GameObject gameOverSet;

UI 변수에 할당

void Update()
{
    curSpawnDelay += Time.deltaTime;
    
    if (curSpawnDelay > maxSpawnDelay)
    {
        SpawnEnemy();
        maxSpawnDelay = Random.Range(0.5f, 2.0f);
        curSpawnDelay = 0;
    }

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

* string.format("포맷", 변) : 지정된 양식으로 문자열을 변환해주는 함수 

                              ex ) string.Format("{0:n0}", playerLogic.score); 같은 형식으로 사용

* "{0:n0}" : 세자리마다 쉼표로 나눠주는 문자열 양

 

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

먼저 라이프 이미지 알파값 0인 상태로 모두 불러옴

그 후 현재 남은 라이프 수 만큼 라이프 알파값 1로 변경

 

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

게임 오버 UI 표시하는 GameOver 함수 작성

 

else if(collision.gameObject.tag == "Enemy" || collision.gameObject.tag == "EnemyBullet")
{
    //무적 상태는 제일 먼저 처리해서 무적 처리
    if (isRespawnTime)
    {
        //리스폰 시간이면 함수 그냥 리턴
        return;
    }
    //
    life--;
    gameManager.UpdateLifeIcon(life);
    if(life == 0)
    {
        gameManager.GameOver();
    }
    else
    {
        gameManager.RespawnPlayer();
    }
    //부딪힌 총알이나 적 디스트로이
    Destroy(collision.gameObject);
    //죽으면서 플레이어 색상 반투명(무적상태) 리스폰 무적 활성화
    spriteRenderer.color = new Color(1, 1, 1, 0.5f);
    isRespawnTime = true;
    gameObject.SetActive(false);
}

 Collision 이벤트에서 라이프 줄이고 라이프 0일 경우 게임오버'

무적 상태 처리를 제일 먼저해서 무적이면 함수 자동 반환되게 함 (라이프도 줄지 않음)

 

변수 초기화

변수 맵핑하고 결과물 확인

결과물 확인

 

리트라이 버튼 구현

재시작을 위해 using UnityEngine.SceneManagement; 를 사용

 

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

LoadScene으로 씬 재시작

 

재시작 기능 on Click 함수에 구현