Menu
CoddyTech

La fine della notte

Fa parte della sezione Creare veri giochi del percorso Unity di Coddy. Lezione 60 di 60.

L’ultima sfida completa un intero gioco: un gestore con stati, una pausa che ferma il tempo, due finali e un riavvio che reimposta la scala temporale.

challenge icon

Sfida

Difficile

Aggiungi una pausa, due finali e un riavvio.

  1. pauseButton alterna solo Playing e Paused: Paused imposta Time.timeScale su 0 e mostra pausePanel, mentre Playing annulla entrambe le operazioni.
  2. A 0 secondi la notte è Won. In caso di Won o Lost: scala temporale impostata su 0, endPanel visualizzato con You survived the night! o The bats got you in endText.
  3. restartButton imposta la scala temporale su 1 e ricarica la scena.

Premi «Gioca», metti in pausa, perdi e gioca di nuovo. Poi premi «Verifica».

Provalo tu

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

public class GameManager : MonoBehaviour
{
    public enum State { Playing, Paused, Won, Lost }

    public static GameManager Instance;

    public float nightLength = 15f;
    public float spawnEvery = 2f;
    public GameObject batPrefab;
    public Transform[] spawnPoints;
    public TMP_Text dawnText;
    public Button pauseButton;
    public GameObject pausePanel;
    public GameObject endPanel;
    public TMP_Text endText;
    public Button restartButton;

    public State state;

    private float timeLeft;
    private float spawnTimer;

    void Awake()
    {
        Instance = this;
    }

    void Start()
    {
        state = State.Playing;
        timeLeft = nightLength;
        ShowDawn();
    }

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

        timeLeft -= Time.deltaTime;
        spawnTimer += Time.deltaTime;
        if (spawnTimer >= spawnEvery)
        {
            spawnTimer -= spawnEvery;
            Transform point = spawnPoints[Random.Range(0, spawnPoints.Length)];
            Instantiate(batPrefab, point.position, Quaternion.identity);
        }
        ShowDawn();
    }

    public void Lose()
    {
        if (state != State.Playing) return;
        state = State.Lost;
    }

    void ShowDawn()
    {
        dawnText.text = "Dawn in " + Mathf.CeilToInt(timeLeft);
    }
}
quiz iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Creare veri giochi

Esercitati da solo: Playground Unity