유니티 게임 개발/Jumping Rabbit

[유니티] Jumping Rabbit #4 일시정지 메뉴, 게임오버 메뉴 만들기

노랑꼬리 2022. 11. 18. 22:50

※ 구현목표

일시정지 메뉴, 게임오버 및 게임 클리어 UI 구현

012

 

1. 메뉴 스크립트

 

메뉴는 자주 사용되고 상황에 따라 다른 동작을 하게 되므로

메뉴 스크립트와 버튼 타입 스크립트 두가지로 나누어 작성하였다.

 

1) 메뉴 스크립트

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
32
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
 
public enum BTNType
{
  Main,
  Continue,
  Retry,
  Quit
}
 
public class MenuUI : MonoBehaviour
{
  public GameObject MenuPanel;
 
  private void Start()
  {
    MenuPanel.SetActive(false);
  }
 
  void Update()
  {
    if (Input.GetKeyDown(KeyCode.Escape))
    {
      Debug.Log("메뉴");
      Time.timeScale = 0;
      MenuPanel.SetActive(true);
    }
  }
}
 
cs

메뉴 타입을 열거형으로 선언해줌으로서 가시성을 높혀주며 이후 버튼이 추가 되어도 쉽게 변경이 가능하다.

 

메뉴는 안드로이드는 취소버튼, PC에서는 ESC키를 누르면 작동하는 KeyCode.Escape 입력시

메뉴 UI가 활성화 되도록 하였다. (게임 시작시 비활성화)

메뉴를 부르며 Time.timeScale로 게임을 정지 시켜주었다. 이는 FixedUpdate가 정지하기 때문에

UI가 작동하는 Update()는 계속 작동하기 때문에 게임 플레이만 일시정지가 가능하다

 

 

2) 버튼 타입 스크립트

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
32
33
34
35
36
37
38
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class ButtonType : MonoBehaviour
{
  public BTNType currentType;
  public GameObject MenuPanel;
 
  public void OnBtnClick()
  {
    switch (currentType)
    {
      case BTNType.Main:
        SceneManager.LoadScene(0);
        Debug.Log("메인");
 
        Time.timeScale = 1.0f;
        break;
      case BTNType.Continue:
        MenuPanel.SetActive(false);
        Time.timeScale = 1.0f;
        Debug.Log("계속");
        break;
      case BTNType.Retry:
        SceneManager.LoadScene(2);
        Time.timeScale = 1.0f;
        Debug.Log("재시작");
        break;
      case BTNType.Quit:
        Application.Quit();
        Debug.Log("종료");
        break;
    }
  }
}
 
cs

 

currentType 파라미터로 입력받은 버튼 타입에 따른 동작을 지정해 주었다.

각 버튼을 눌렀을 때

씬 이동, Pause 끝내기, 씬 재시작, 게임 종료 기능을 넣었다.

 

 

 

2. 게임클리어 및 게임 오버

 

클리어는 최상단 보물상자에 도달하면 게임이 정지되고 클리어 UI가 나타나게 하였다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
public class Clear : MonoBehaviour
{
  Animator anim;
 
  public GameObject ClearPanel;
 
  void Start()
  {
    anim = GetComponent<Animator>();
    ClearPanel.SetActive(false);
  }
 
  private void OnTriggerEnter2D(Collider2D collision)
  {
    if (collision.gameObject.tag == "Player")
    {
      Time.timeScale = 0;
      ClearPanel.SetActive(true);
    }
  }
 
}
cs

 

게임오버의 경우 하드모드에서만 구현하였다.

 

1
2
3
4
5
6
7
8
  private void OnTriggerEnter2D(Collider2D collision)
  {
    if (collision.gameObject.tag == "Player")
    {
      Invoke("TimeStop"7);
      Handheld.Vibrate();
      GameOverPanel.SetActive(true);
    }
cs

플레이어와 부딧히면 게임오버 UI가 나타나며 게임이 7초뒤에 종료된다.

 

하드모드의 자세한 내용은 (https://yellowtail2357.tistory.com/27)에서 다룬다.