인텔리킴의 Unity Studying & Game Analysis
28. 유니티 2D 종스크롤 슈팅 - UI 작성 본문
목숨과 점수 UI 배치
먼저 플레이어 로직에 목숨, 점수 로직 추가
* Scale With Screen Size : 기존 해상도의 UI 크기 유지
* Canvas Scaler 기준 해상도 값 설정
버튼 UI는 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으로 씬 재시작
'게임 개발 일지 > 유니티 엔진 공부' 카테고리의 다른 글
30. 유니티 2D 종스크롤 슈팅 - 무한 배경 만들기 (0) | 2024.06.03 |
---|---|
29. 유니티 2D 종스크롤 슈팅 - 아이템, 필살기 구현 (0) | 2024.05.31 |
27. 유니티 2D 종스크롤 슈팅 - 적 전투와 피격 이벤트 (0) | 2024.05.24 |
26. 유니티 2D 종스크롤 슈팅 - 적 유닛 만들기 (0) | 2024.05.23 |
25. 유니티 2D 종스크롤 슈팅 - 총알 발사 구현 (0) | 2024.05.13 |