1
\$\begingroup\$

I edited my question. I hope this will make things more clear. If not please let me know.

I have two scenes: MainMenu and Game. MainMenu is the first Scene loaded when my game starts. MainMenu contains 3 buttons (inside a Canvas) and my GameController object that has this script attached:

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class GameController : MonoBehaviour
{
     public static GameController instance;
     private GameObject playerShip;

    void Awake()
    {
        if (instance == null)
        {
            instance = this;
            DontDestroyOnLoad(gameObject);
        }
        else if (instance != this)
        {
            DestroyImmediate(gameObject);
        }
    }

    public void loadScene(string sceneName)
    {
        SceneManager.LoadScene(sceneName);
    }

    public void quitGame()
    {
        Application.Quit();
    }

    public void setPlayerShip(GameObject playerShip)
    {
        this.playerShip = playerShip;// Instantiate<GameObject>(playerShip);
        Debug.Log("Set Player Ship to " + playerShip.name);
    }

    public GameObject getPlayerShip()
    {
        Debug.Log("Returned PlayerShip " + playerShip.name);
        return this.playerShip;
    }
}

One of the buttons (Start_Button) starts the game and is configured as follows:

enter image description here

When I start my game, the MainMenu is loading and by clicking on the Start_Button the Game is loaded. Game also contains a GameController object with the following LevelController script:

using UnityEngine;
using UnityEngine.SceneManagement;
using System.Collections;

public class LevelController: MonoBehaviour {
    [Tooltip("An Array of Hazards that can be spawned")]
    public GameObject[] hazards;

    public Vector3 spawnValues;

    public int hazardCount;
    [Tooltip("Time in Seconds between spawning 2 hazards")]
    public float spawnRate;
    [Tooltip("Time before 1st wave starts. And Time between Waves.")]
    public float startWait;

    private int scorePoints;

    public UnityEngine.UI.Text scoreText;

    public UnityEngine.UI.Text restartText;

    private bool gameOver;
    private bool restart;


    // Use this for initialization
    void Start () {
        GameObject playerShip = Instantiate<GameObject>(GameController.instance.getPlayerShip());
        playerShip.transform.position = new Vector2(Screen.width / 2, Screen.height / 2);
        Init();
    }
    void Init()
    {
        scorePoints = 0;
        gameOver = false;
        restart = false;
        restartText.text = "";
        updateScore();
        StartCoroutine(spawnWaves());
    }

    // Update is called once per frame
    void Update () {
        if(restart && Input.GetKeyUp(KeyCode.Escape))
        {
            SceneManager.LoadScene("MainMenu");
        }
    }

    IEnumerator spawnWaves()
    {
        yield return new WaitForSeconds(startWait);
        while (!gameOver) {
            for (int i = 0; i < hazardCount; i++)
            {
                Vector3 spawnPosition = new Vector3(spawnValues.x, Random.Range(-spawnValues.y, spawnValues.y), spawnValues.z);
                Quaternion spawnRotation = Quaternion.identity;
                int random = Random.Range(0, hazards.Length);
                Instantiate(hazards[random], spawnPosition, spawnRotation);
                yield return new WaitForSeconds(spawnRate);
            }
            yield return new WaitForSeconds(startWait);

        }
    }

    void updateScore()
    {
        if (scoreText != null)
        {
            scoreText.text = "Score: " + scorePoints;
        }
        else
        {
            Debug.LogError("Cannot find 'GUIText' for updating Scoretext.");
        }
    }

    public void addToScore(int scoreValue)
    {
            scorePoints += scoreValue;
            updateScore();
    }

    public void setGameOver()
    {
        gameOver = true;
        restartText.text = "GAME OVER \n Hit ESC to get back to the Menu.";
        restart = true;
    }
}

When the game is over and the player hits the "ESC" key the MainMenu will be loaded. This works fine so far. If I'm clicking the Start_Button again nothing happens. What am I doing wrong?

If you like you can even check out the full project on github

\$\endgroup\$
  • \$\begingroup\$ Can you explain your problem in more detail? As it stands, you describe that if you start in Game, and move to MainMenu, you can not move back to Game. Having tested this myself, it does not behave as you explain. In fact, I can freely move back and forth between Game and MainMenu. For questions like this to be on topic, you must provide a minimal example of your code that allows us to replicate your problem. \$\endgroup\$ – Gnemlock Oct 25 '16 at 12:58
  • \$\begingroup\$ @Gnemlock I edited my question so that it is hopefully more clear what is happening and that you are able to replicate the problem. Besides that I'd really like to know why my question got downvoted? \$\endgroup\$ – Naxos84 Oct 25 '16 at 18:40
  • \$\begingroup\$ It looks to me like your Start Game button is wired up to the GameController object that exists in its scene. The first time you load the scene, everything works great. When you reload the scene, the Start Game button that loads is pointing to the GameController that loaded alongside it in the newest version of this scene. That GameController immediately kills itself because it's not the saved static instance, leaving your Start Game button pointing at nothing, because you haven't told it to relink itself to the inherited GameController from the last time the scene was loaded. \$\endgroup\$ – DMGregory Oct 25 '16 at 19:56
  • \$\begingroup\$ @DMGregory Ok. I think I understand what you're trying to say but I don't get any error messages from Unity. And the more important question: how can I fix this issue? \$\endgroup\$ – Naxos84 Oct 26 '16 at 5:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.