Menu
CoddyTech

ベスト記録

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

challenge icon

チャレンジ

中級

最後のステップ:最高記録を保存しましょう。これまでのレッスンの内容はすべてそのまま使います。キャンバスの右上には BestText があり、パネルには非表示の NewBestText(New best!)があります。シーンでは、これらを GameManager の新しいフィールド public TMP_Text bestText; と public GameObject newBestText; に設定します。最高記録はキー BestRun で、メートル単位の整数として保存します。

  • Start() で最高記録を読み込み(新しいプレイヤーの場合は 0)、Best: 57 m のように表示します。
  • GameOver() で、今回の走行距離のメートル単位の整数 Mathf.FloorToInt(distance) が最高記録を上回った場合は、新しい最高記録を保存して表示し、newBestText を表示します。より短い走行では何も変わりません。

最高記録は「もう一度走る」を選んでも、ゲームを終了しても保持されます。Play を押して最高記録を作り、それを更新してみてから、Check を押してください。

自分で試してみよう

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;
    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);
    }
}

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