Unity
스코어
코딩 화이팅
2023. 10. 18. 15:47
GameOverScene에 Score에 새로운 컴포넌트를 하나 만들어준다.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CurrentScore : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
GetComponent<Text>().text = "Score : "+Score.score.ToString();
}
}
Score는 스코어를 불러오는 코드를 작성해준다.
게임 시작할 때 스코어를 0으로 해주기
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
//using UnityEngine.UI; : 스코어가 바뀔 때마다 UI적 요소의 변화를 주기 위해 using을 해줘야된다.
public class Score : MonoBehaviour
{
public static int score = 0;
//static을 붙여줌으로써 다른 클래스에서도 score를 조절가능하다.
// Start is called before the first frame update
void Start()
{
score = 0;
}
// Update is called once per frame
void Update()
{
GetComponent<Text>().text = score.ToString();
//GetComponent: Component를 들고와줌.
//ToString : int형을 string으로 변환
}
}
Start()를 통해 score를 0으로 초기화해주면 시작 시 0으로 시작할 수 있다.
베스트 스코어
부딪혔을 때 나오는 스코어를 베스트 스코어와 비교하여 베스트 스코어가 스코어 보다 크다면 스코어를 베스트 스코어 점수로 바꿔줌.
private void OnCollisionEnter2D(Collision2D collision)
//OnCollisionEnter2D : 부딪히는 이벤트에 사용되는 메소드
{
if(Score.score>Score.bestscore) Score.bestscore=Score.score;
SceneManager.LoadScene("GameOverScene");
}
이렇게 해서 베스트 스코어를 수정해주고
이제 베스트 스코어에 수정해준 베스트 스코어가 나오도록 해줌
Best Score의 객체 안에 새로운 컴포넌트를 만들어줌
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class BestScore : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
GetComponent<Text>().text = "Best Score : " + Score.bestscore;
}
// Update is called once per frame
void Update()
{
}
}
새가 하늘 위로 올라가면 게임이 끝나도록
새로운 객체를 만들고 새로운 Box collider2D 컴포넌트를 만들어줌. 그리고 Offset과 Size를 조절하여 하늘 위에 부딪히면 게임이 끝나도록 조절해준다.