1 minute read

Unity:汎用スコア管理システム的なプロトタイプを作った

全てのプロジェクトに一からスコア管理システム作るとか、

正気じゃないので作らざるを得なかった。

とりあえず下記のような感じにして、

各プロジェクト毎に追記する形になるだろうか?

改良の余地は多い、もっと良いコードを書こう。

※TextMeshProの部分は必要に応じて変更が必要です。

Controller Class


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

public class ScoreController : MonoBehaviour {


	Score scoreObj;

	TextMeshProUGUI textmeshPro;

	void Awake()
	{
		scoreObj = GameObject.FindWithTag("ScoreText").GetComponent<Score>();
		textmeshPro = GameObject.FindWithTag("ScoreText").GetComponent<TextMeshProUGUI>();
	}

	// Use this for initialization
	void Start ()
	{

	}

	// Update is called once per frame
	void Update ()
	{
		// Debug.Log(getScore());
		if(textmeshPro != null) {
			textmeshPro.SetText("ChangeText");
			textmeshPro.SetText(this.getScore().ToString());
		}
	}

	void FixedUpdate()
	{

	}

	public int getScore()
	{
		return scoreObj.score;
	}
	public void setScore(int var)
	{
		scoreObj.score = var;
	}
	public void addScore(int var)
	{
		scoreObj.score += var;
	}
	public void subtScore(int var)
	{
		int result = this.getScore() - var;
		scoreObj.score = (result <= 0) ? 0 : result;
	}
	public void saveNowScore()
	{
		PlayerPrefs.SetInt(scoreObj.scoreKey, this.getScore());
	}
	public void loadNowScore()
	{
		if(PlayerPrefs.GetInt(scoreObj.scoreKey) == null) {
			setScore(0);
			return;
		}

		int nowScore = PlayerPrefs.GetInt(scoreObj.scoreKey);
		setScore(nowScore);
		Debug.Log("now: " + this.getScore());

	}

	public int getHighScore()
	{
		return scoreObj.highScore;
	}
	public void setHighScore(int var)
	{
		scoreObj.highScore = var;
	}
	public void saveHighScore()
	{
		this.loadHighScore();

		int nowScore = this.getScore();
		if (nowScore > this.getHighScore()) {
			PlayerPrefs.SetInt(scoreObj.highScoreKey, nowScore);
		}

	}
	public void loadHighScore()
	{
		int loadHighScore = 0;

		if(PlayerPrefs.GetInt(scoreObj.highScoreKey) == null) {
			setHighScore(loadHighScore);
			return;
		}

		loadHighScore = PlayerPrefs.GetInt(scoreObj.highScoreKey);
		setHighScore(loadHighScore);
		Debug.Log("high: " + this.getHighScore());

	}



}


Score Class

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

public class Score : MonoBehaviour {

	public int score { get; set; }
	public int highScore { get; set; }
	public string scoreKey = "SCORE";
	public string highScoreKey = "HIGHSCORE";

}