Play Again button not working

My play again button is connected to the LoadGame method. I have Game Session and Level game objects in all of the scenes . My Main Menu → Start button works well (although I had to modify the code and wrote static in order to reset itself). I can’t seem to find the problem. I think my gameObject isn’t getting destroyed correctly.

//Level
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;

public class Level : MonoBehaviour
{
    [SerializeField] float delayInSeconds = 2f;
    GameSession gameSession;

   public void LoadStartMenu()
    {
        SceneManager.LoadScene(0);
    }

    public void LoadGame()
    {
        SceneManager.LoadScene(1);
        FindObjectOfType<GameSession>().ResetGame();
        Debug.Log("Game Session Reset");
        Debug.Log(FindObjectOfType<GameSession>().GetScore());
    }

    public void LoadGameOver()
    {
        StartCoroutine(WaitAndLoad());
    }

    IEnumerator WaitAndLoad()
    {
        yield return new WaitForSeconds(delayInSeconds);
        SceneManager.LoadScene("Over");
    }


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

}

// Game Session
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameSession : MonoBehaviour
{
    static int score = 0;

    private void Awake()
    {
        SetUpSingleton();
    }

    private void SetUpSingleton()
    {
        int numberGameSessions = FindObjectsOfType<GameSession>().Length;
        if (numberGameSessions > 1)
        {
            Destroy(gameObject);
        }
        else
        {
            DontDestroyOnLoad(gameObject);
        }      
    }

    public int GetScore()
    {
        return score;
    }

    public void AddToScore(int scoreValue)
    {
        score += scoreValue;
    }

    public void ResetGame()
    {
        Destroy(gameObject.gameObject);
    }

}

Hi Emilia,

Check if your “singleton” calls gameObject.SetActive(false); in the same if-block where Destroy(gameObject); gets called. If there isn’t that line of code, add it.


See also:

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms