Skip to content

1 ‐ GameManger

문현우 edited this page Sep 13, 2023 · 4 revisions

📌 GameManager

🎇 Managed by 조영오

  • Unity 게임에서 게임 흐름을 관리하고 플레이어의 상태, 점수, 적 생성, 게임 종료등 게임의 총괄적인 부분을 담당하는 역할을 합니다.

📜 Code Summary

  • Awake()

    • Unity 게임 오브젝트가 활성화하기 전에 호출되는 부분입니다.
    • 게임 매니저의 인스턴스를 설정하여, 다른 스크립트에서 GameManager에 접근할 수 있게됩니다.
  • Start()

    • 게임 오브젝트가 활성화 된 후 호출됩니다.
    • 선택한 캐릭터를 로드하고 게임의 초기 설정을 담당하는 메서드입니다.
    • 적을 생성하는 SpawnEnemy() 메서드를 주기적으로 호출하고, 게임을 시작합니다.
  • Update()

    • 매 프레임마다 호출되는 부분입니다.
    • 플레이어의 체력이 0보다 크면 게임이 진행중으로 인식하며, PlaingGame() 메서드를 호출하여 점수를 증가시킵니다.
    • 플레이어의 체력이 0이 되면 게임 종료 처리를 수행하고, GameOver() 메서드를 호출하여 게임을 종료시킵니다.
  • StartGame()

    • 게임을 시작할 때 호출되는 메서드입니다.
    • 타임 스케일을 원래 속도로 설정하고 점수를 초기화합니다.
    • 플레이어의 최대 체력을 가져와서 라이프 아이콘을 초기화합니다.
    • 배경 음악을 재생하고 적 생성합니다.
  • PlayingGame()

    • 게임 중에 호출되는 메서드입니다.
    • 점수를 증가시킵니다.
  • SpawnEnemy()

    • 적 캐릭터를 생성하는 메서드입니다.
    • EnemyManager 클래스의 SpawnEnemy() 메서드를 호출하여 적을 생성합니다.
  • HitPlayer()

    • 플레이어가 피해를 입었을 때 호출되는 메서드입니다.
    • 효과음을 재생하고 플레이어의 남은 체력을 화면에 업데이트합니다.
  • TakePotion()

    • 플레이어가 포션을 먹었을 때 호출되는 메서드입니다.
    • 포션을 먹은 효과음을 재생하고 플레이어의 체력을 화면에 업데이트합니다.
  • PrintLife(int life)

    • 플레이어의 체력을 화면에 표시하는 메서드입니다.
    • 라이프 아이콘을 활성화 또는 비활성화하여 플레이어의 현재 체력을 표시합니다.
  • GetLifeList(int maxLife)

    • 플레이어의 최대 체력에 따라 라이프 아이콘을 생성하고 위치를 설정하는 메서드입니다.
  • GameOver()

    • 게임이 종료될 때 호출되는 메서드입니다.
    • 배경 음악을 중지하고 게임 오버 화면을 표시합니다.
    • 최고 점수를 업데이트하고 현재 점수를 표시합니다. 최고 점수는 PlayerPrefs를 사용하여 저장합니다.

💻 Code

GameManager.cs
using UnityEngine;
using UnityEngine.UI;

public class GameManager : MonoBehaviour
{
    static GameManager instance;
    public static GameManager Instance { get { return instance; } }
    public GameObject stageUI;
    public Text scoreUI;
    public Text lifeUI;
    public Text highScoreUI;
    public Text currentScoreUI;
    public GameObject resultUI;
    private float score = 0f;
    private int maxLife;
    private bool isGameOver = false;

    private GameObject[] lifeList;
    private Player player;


    void Awake()
    {
        if (instance == null)
        {
            instance = this;
        }
    }

    void Start()
    {
        int selectedCharacterIndex = PlayerPrefs.GetInt("SelectedCharacterIndex", -1);
        PlayerManager playerManager = FindObjectOfType<PlayerManager>();
        if (playerManager != null && selectedCharacterIndex != -1)
        {
            PlayerType selectedPlayerType = (PlayerType)selectedCharacterIndex;
            player = playerManager.CreatePlayer(selectedPlayerType);

            maxLife = player.Hp;
            lifeList = new GameObject[maxLife];
        }

        InvokeRepeating("SpawnEnemy", 1f, 1f);

        StartGame();
    }

    void Update()
    {
        if (player.Hp > 0)
        {
            PlayingGame();
        }
        else if(!isGameOver)
        {
            isGameOver = true;
            GameOver();
        }
    }

    public void StartGame()
    {
        Time.timeScale = 1f;
        score = 0f;
        GetLifeList(maxLife);
        PrintLife(player.Hp);
        scoreUI.text = ((int)score).ToString();
        isGameOver = false;

        AudioManager.instance.PlayBgm(false);
        AudioManager.instance.PlayBgm(true);

        for (int i = 0; i < 36; i++)
        {
            SpawnEnemy();
        }
    }

    private void PlayingGame()
    {
        score += 0.1f;
        scoreUI.text = ((int)score).ToString();
    }

    private void SpawnEnemy()
    {
        EnemyManager.Instance.SpawnEnemy();
    }

    public void HitPlayer()
    {
        AudioManager.instance.PlaySfx(AudioManager.Sfx.Hit);
        PrintLife(player.Hp);
    }

    public void TakePotion()
    {
        AudioManager.instance.PlaySfx(AudioManager.Sfx.Range);
        PrintLife(player.Hp);
    }

    private void PrintLife(int life)
    {
        for (int i = 0; i < lifeList.Length; i++)
        {
            if (i <= life - 1)
            {
                lifeList[i].SetActive(true);
            }
            else
            {
                lifeList[i].SetActive(false);
            }
        }
    }

    private void GetLifeList(int maxLife)
    {
        Vector3 lifePosition = new Vector3(-12f, 8.7f, 0f);

        for (int i = 0; i < maxLife; i++)
        {
            lifePosition.x += 1.5f;
            lifeList[i] = LifeManager.instance.CreateLife(lifePosition);
        }
    }

    private void GameOver()
    {

        
        AudioManager.instance.PlayBgm(false);
        Time.timeScale = 0f;
        resultUI.SetActive(true);
        AudioManager.instance.PlaySfx(AudioManager.Sfx.Win);
        if (!PlayerPrefs.HasKey("highScore"))
        {
            PlayerPrefs.SetInt("highScore", (int)score);
        }
        else if(PlayerPrefs.GetInt("highScore") < (int)score)
        {
            PlayerPrefs.DeleteKey("highScore");
            PlayerPrefs.SetInt("highScore", (int)score);
        }

        highScoreUI.text = PlayerPrefs.GetInt("highScore").ToString();
        currentScoreUI.text = ((int)score).ToString();
    }
}

Clone this wiki locally