프로젝트해요/게임_개발

[Unity] #8. 슈팅 게임 제작(4)

yenas0 2023. 7. 6. 06:37
반응형

 

 

이번에는 현재점수를 기록하고 최고점수를 저장하는 기능을 만들어 보도록하자.

 

 

 


 

- 화면 표시

 

[Hierarchy] - [UI] - [Text] 를 클릭한다.

 

 

 

Canvas 하위에 생긴 Text 오브젝트의 이름을 CurrentScore로 변경한다.

 

 

 

 

 

텍스트 창에 현재점수라고 표시 될 수 있도록 작성한다.

 

 

 

 

우주배경을 사용하였기 때문에 검정색 글씨의 경우 잘 안보인다. 하얀색 글씨로 색상을 변경한다.

 

 

 

 

기본 위치는 좌측하단에 표시되었으나 좌측 상단으로 텍스트 위치를 변경시킨다.

 

 

 

 

게임화면에는 다음과 같이 표시된다.

 

 

 

 

 

 

동일한 방법으로 최고점수 항목도 만들어준다.

 

 

 

 

 

 

 

- 스크립트 작성

 

 

점수를 기록하고 저장하는 기능을 사용하기 위해서 ScoreManager 스크립트와 Empty Object를 생성한다.

 

 

 

 

다음과 같은 스크립트를 작성해준다.

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

public class ScoreManager : MonoBehaviour
{
    public Text currentScoreUI;
    public int currentScore;

    public Text bestScoreUI;
    public int bestScore;

    // Start is called before the first frame update
    void Start()
    {
        bestScore = PlayerPrefs.GetInt("Best Score", 0);
        bestScoreUI.text = "최고점수 : " + bestScore;
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

 

 

 

 

 

적을 미사일로 폭발 시킬시 점수가 올라가야하므로 Enemy 스크립트도 다음과 같이 수정한다.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Enemy : MonoBehaviour
{
    public float speed = 5;

    Vector3 dir;

    public GameObject explosionFactory;

    // Start is called before the first frame update
    void Start()
    {
        int randValue = Random.Range(0, 10); //0부터 9까지의 값만 나온다

        if(randValue < 3)
        {
            GameObject target = GameObject.Find("Player");

            dir = target.transform.position - transform.position; //적과 플레이어 거리 벡터 계산
            dir.Normalize(); //단위벡터로 바꿈
        }
        else
        {
            dir = Vector3.down;
        }
    }

    // Update is called once per frame
    void Update()
    {
        transform.position += dir * speed * Time.deltaTime;
    }

    void OnCollisionEnter(Collision other)
    {
        GameObject smObject = GameObject.Find("ScoreManager");

        ScoreManager sm = smObject.GetComponent<ScoreManager>();

        sm.currentScore++;

        sm.currentScoreUI.text = "현재점수 : " + sm.currentScore;

        if (sm.currentScore > sm.bestScore)
        {
            sm.bestScore = sm.currentScore;
            sm.bestScoreUI.text = "최고점수 : " + sm.bestScore;

            PlayerPrefs.SetInt("Best Score", sm.bestScore);
        }

        GameObject explosion = Instantiate(explosionFactory);

        explosion.transform.position = transform.position;

        Destroy(other.gameObject);
        Destroy(gameObject);
    }
}

 

 

 

 

스크립트 작성을 완료했다면 ScoreManager 오브젝트를 클릭한 뒤 다음의 항목에  앞서 만든 텍스트를 적용시킨다.

 

 

 

 

 

최종적으로 게임을 실행시키면 다음과 같이 현재점수와 최고점수가 표시된다.

 

 


 

점수 만들고 나니까 더 게임같은 느낌이 드는 것 같아서 좋다~

근데 오늘 유니티 실행하는데 파일 다 날라간줄알고 진짜 깜짝 놀랐다..,.,

 

 

 

 

 

 

 

반응형