반응형

이번 시간에는 게임 뷰에 점수를 보이게 하겠습니다

먼저 Hierarchy 뷰에서 마우스 오른쪽 버튼을 클릭하고   UI -> Text를 생성합니다 

그러면 Hierarchy 뷰에서 Canvas 가 생성됩니다 

Canvas 를 선택하고  UI Scale Mode -> Scale With Screen Size , Reference Resolution  1080 1920 , Match 0.5에 맞춥니다 

 

Canvas 자식으로 있는 Text 의 이름을 ScoreText로 바꾸고 ScoreText를 선택하여 Center를 클릭한 다음 아래 사진처럼 top 중앙에 올 수 있도록 합니다 

 

그리고 Canvas 를 클릭하고 마우스 오른쪽을 클릭하고 Create Empty 하여 GameObject를 생성한 다음 이름을 GameUI로 고친 후 ScoreText를 자식으로 놓습니다 

GameManager 스크립트를 수정합니다 

 

점수 Text 를 넣을 수 있는 네임스페이스(using UnityEngin.UI)를 추가하고 변수에 int score = 0 , pulic Text scoreText 추가 GameStart() 함수에 gameUI.SetActive(true)   StartCoroutine(UpdateScore()) 추가

 IEnumerator UpdateScore()
    {
        //1초 지날때 마다 1점씩 올라간다 
        while (true)
        {
            yield return new WaitForSeconds(1f);
            score++;

            scoreText.text = score.ToString();
        }
    }

 

추가 합니다 

 

반응형

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;


public class GameManager : MonoBehaviour
{
    public static GameManager instance;

    //
    public GameObject platformSpawner;

    public GameObject gameUI;

    public bool gameStarted;

    int score = 0;

    public Text scoreText;

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

    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (!gameStarted)
        {
            //마우스 클릭하면 차가 움직인다 
            if (Input.GetMouseButtonDown(0))
            {
                GameStart();
            }
        }
    }

    public void GameStart()
    {
        gameStarted = true;
        //platformSpawner 스크립트를 실행
        platformSpawner.SetActive(true);

        gameUI.SetActive(true);
        StartCoroutine(UpdateScore());
    }


    public void GameOver()
    {
        //platformSpawner 스크립트를 없앤다
        platformSpawner.SetActive(false);

        //1초후 게임재시작 함수에 전달 
        Invoke("ReloadGame",1);
    }

    //게임재시작
    void ReloadGame()
    {
        SceneManager.LoadScene("Game");
    }

    IEnumerator UpdateScore()
    {
        //1초 지날때 마다 1점씩 올라간다 
        while (true)
        {
            yield return new WaitForSeconds(1f);
            score++;

            scoreText.text = score.ToString();
        }
    }
}

 

Hierarchy 뷰에서 Canvas 자식으로 있는 GameUI를 끄고 GameManager를 선택하여 GameUI와 ScoreText를 연결합니다 

 

게임을 실행하여 점수가 올라가는지 확인합니다 

 

반응형

+ Recent posts