Menu
CoddyTech

もう一度走る

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

challenge icon

チャレンジ

中級

もう一度実行ボタンで新しいプレイを開始できるようにします。

  1. GameManagerに、シーンを再読み込みするvoid Restart()を記述します: SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);。
  2. restartButton.onClick.AddListener(Restart);を含むvoid Start()を追加します。

「プレイ」を押し、衝突したら「もう一度実行」をクリックします。新しいプレイが始まります。その後、「確認」を押します。

自分で試してみよう

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

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

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