Menu
CoddyTech

ベストラン

CoddyのUnityジャーニー「本格的なゲームを作る」セクションの一部。レッスン 33/60。

Endless Runnerの最後のステップです。最高記録は、ハイスコアと同じようにPlayerPrefsに保存されるため、「もう一度実行」したりゲームを終了したりしても残ります。

challenge icon

チャレンジ

中級

最高記録をキー BestRun に保存します。

  1. private int best; を追加します。Start() で PlayerPrefs.GetInt("BestRun", 0) を使って読み込み、bestText に "Best: " + best + " m" を表示します。
  2. GameOver() の最後に、Mathf.FloorToInt(distance) が best を上回ったら、それを保存して表示し、newBestText.SetActive(true); を呼び出します。

「プレイ」を押して最高記録を出し、その記録を更新すると、「New best!」と表示されます。その後、「確認」を押します。

自分で試してみよう

using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;
using TMPro;

public enum GameState { Playing, GameOver }

public class GameManager : MonoBehaviour
{
    public static GameManager Instance;

    public float speed = 10f;
    public float speedUp = 0.5f;
    public float maxSpeed = 20f;
    public TMP_Text distanceText;
    public GameObject gameOverPanel;
    public Button restartButton;
    public GameState state = GameState.Playing;
    public TMP_Text bestText;
    public GameObject newBestText;
    private float distance;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        restartButton.onClick.AddListener(Restart);
    }

    void Update()
    {
        if (state != GameState.Playing) return;

        speed = Mathf.Min(speed + speedUp * Time.deltaTime, maxSpeed);
        distance += speed * Time.deltaTime;
        distanceText.text = "Distance: " + Mathf.FloorToInt(distance) + " m";
    }

    public void GameOver()
    {
        state = GameState.GameOver;
        speed = 0f;
        gameOverPanel.SetActive(true);
    }

    void Restart()
    {
        SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
    }
}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

本格的なゲームを作るのすべてのレッスン

自分で練習してみよう: Unityプレイグラウンド