Menu
CoddyTech

撞毁后本局结束

本课属于 Coddy Unity 学习旅程的“打造真正的游戏”单元。第 31 课,共 60 课。

challenge icon

挑战

中等

发生碰撞后,运行应停止。

  1. 在 GameManager 上方声明 public enum GameState { Playing, GameOver };在其中添加 public GameState state = GameState.Playing;。
  2. public void GameOver() 将 state 设为 GameState.GameOver,将 speed 设为 0,并显示 gameOverPanel。
  3. 当触发器的标签为 Obstacle 时,Runner 调用 GameManager.Instance.GameOver()。GameManager、Runner 和 Spawner 的 Update() 都以条件判断开始,如果不是 Playing,就执行 return。

按“开始”,然后发生碰撞:一切都会停止。接着点击“检查”。

亲手试试

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

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;
    private float distance;

    void Awake()
    {
        Instance = this;
    }

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

打造真正的游戏中的所有课

自己练习: Unity 在线编辑器