Menu
CoddyTech

Chạy lại

Thuộc phần Xây dựng trò chơi thực tế trong hành trình Unity của Coddy. Bài học 32 trên 60.

challenge icon

Thử thách

Trung bình

Để nút Chạy lại bắt đầu một lượt chạy mới.

  1. Trong GameManager, viết void Restart() để tải lại cảnh: SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);.
  2. Thêm void Start() với restartButton.onClick.AddListener(Restart);.

Nhấn Chơi, va chạm rồi nhấn Chạy lại: một lượt chạy mới bắt đầu. Sau đó nhấn Kiểm tra.

Tự làm thử

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

Tất cả bài học trong Xây dựng trò chơi thực tế

Tự luyện tập: Playground Unity