Search Unity

Why does the game not restart when the following code is used? 2019.1.10.1f

Discussion in 'Scripting' started by christianlance85, Oct 7, 2019.

  1. christianlance85

    christianlance85

    Joined:
    Oct 2, 2019
    Posts:
    2
    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.SceneManagement;

    public class GameManager : MonoBehaviour
    {
    public static GameManager gm;
    public PlayerControler pc;
    public CameraController cam;
    public MenuManager ui;


    public bool started;
    public bool gameOver;

    public float gravity = 10f;
    public float time = 120f; // Total game time in seconds

    private void Awake()
    {
    if (!gm)
    {
    gm = this;
    DontDestroyOnLoad(this);
    }
    }

    public void Play()
    {
    started = true;
    }

    public void GameOver()
    {
    gameOver = true;
    ui.gameplay.SetActive(false);
    ui.gameOver.SetActive(true);
    ui.finalScoreText.text = pc.score.ToString();
    ui.finalBestText.gameObject.SetActive(true);

    var curBest = PlayerPrefs.GetInt("best");
    if (pc.score > curBest)
    {
    PlayerPrefs.SetInt("best", pc.score);

    ui.finalBestText.gameObject.SetActive(true);
    }

    }


    private void Update()
    {
    if (Input.GetKey(KeyCode.R))
    {
    RestartScene();
    }

    if (!started || gameOver)
    {
    return;

    }


    time -= Time.deltaTime;

    if (time <= 1)
    {
    GameOver();
    ui.timerText.text = "00:00";
    return;
    }

    var minutes = Mathf.FloorToInt(time / 60f);
    var seconds = Mathf.FloorToInt(time - minutes * 60f);
    ui.timerText.text = string.Format("{0:0}:{1:00}", minutes, seconds);
    }

    public void RestartScene()
    {


    SceneManager.LoadScene(SceneManager.GetActiveScene().name);

    }

    }
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Use code tags when you post code to the forums. Are you getting any error messages? Is the scene you are loading in build settings?
     
  3. Antypodish

    Antypodish

    Joined:
    Apr 29, 2014
    Posts:
    10,780
  4. christianlance85

    christianlance85

    Joined:
    Oct 2, 2019
    Posts:
    2
    There aren't any errors, it will reset the scene, but the timer and score no longer works and it won;t let you actually replay the level.
     
  5. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Well you're setting DontDestroyOnLoad on this manager, so it exists with all its current values through the scene reload. I don't see anywhere in your code where you're resetting those when you reload the scene. You're code is difficult to read the way you've posted it though.