Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Game Over script problem

Discussion in 'Scripting' started by popanuu, May 5, 2019.

  1. popanuu

    popanuu

    Joined:
    Feb 20, 2019
    Posts:
    1
    Hello! I have a little problem, so I made the script with the static bool on GameIsOver, tell me why this happens and how to fix it, have a nice day!

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.SceneManagement;
    using UnityEngine.UI;

    public class GameManager : MonoBehaviour
    {
    public GameObject GameOverUI;
    public static bool GameIsOver = false;
    public static bool LevelIsWon = false;
    public string NextLevel = "Level 2";
    public int LevelToUnlock = 2;
    public GameObject LevelWon;


    private void Update()
    {
    if (GameIsOver)
    {
    Restart();
    }else
    {

    }
    }

    public void Restart()
    {
    GameIsOver = true;
    GameOverUI.SetActive(true);
    Time.timeScale = 0f;
    Debug.Log("level is over");


    }

    public void RestartButton()
    {
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    Time.timeScale = 1f;
    GameIsOver = false;
    GameOverUI.SetActive(false);
    }

    public void WinLevel()
    {
    LevelWon.SetActive(true);
    PlayerPrefs.SetInt("LevelReached", LevelToUnlock);
    }

    public void Next()
    {
    SceneManager.LoadScene("LevelSelector");
    }

    }

    https://imgur.com/a/01d0ekA
     
  2. APSchmidtOfOld

    APSchmidtOfOld

    Joined:
    Aug 8, 2016
    Posts:
    4,473
  3. Grankor

    Grankor

    Joined:
    Mar 2, 2015
    Posts:
    14
    Hard to tell from this code what is causing that.

    My guess is that in the inspector, you have GameIsOver set to true.
    If that's the case it doesn't matter what you put here.
    Code (CSharp):
    1. public static bool GameIsOver = false;
    I'm going to make an assumption that it is public because you want to be able to access it from other objects.

    If that's the case, change it to this:
    Code (CSharp):
    1.  
    2. [System.NonSerialized]
    3. public static bool GameIsOver = false;
    4.  
    This will make it disappear from the editor, so it can't be changed.
    (Don't know if it needs to be static, but that's another conversation)

    Another option, is set the field in the Start or Awake method.
    Code (CSharp):
    1.  
    2. private void Start()
    3. GameIsOver = false;
    4.  
    Good luck!