My Hierarchy have 3 main GameObjects :
Game Data where all the gameplay objects are stored as childs of the Game Data GameObject.
Main Menu and all objects of the main menu stored as childs under the Main Menu GameObject.
Game Manager GameObject that have a script that control the game like pausing the game or go to the main menu.
By default the Game Data is disabled and all the gameplay objects childs disabled too. Then when starting the game with the main menu when clicking the button to start a new game I'm just activating the Game Data object :
This script is attached to the Main Menu :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class MainMenu : MonoBehaviour
{
public GameObject gameData;
public void StartNewGame()
{
gameData.SetActive(true);
}
public void ResumeGame()
{
}
public void QuitGame()
{
Application.Quit();
}
}
This is working for first time starting a new game.
And this script is attached to the Game Manager GameObject :
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class GameController : MonoBehaviour
{
public static bool gamepaused = false;
public GameObject gameData;
public GameObject mainMenu;
private void Update()
{
if (Input.GetKeyDown(KeyCode.P))
{
gamepaused = !gamepaused;
if (gamepaused)
{
Time.timeScale = 0f;
}
else
{
Time.timeScale = 1f;
}
}
if (Input.GetKeyDown(KeyCode.Escape))
{
gameData.SetActive(false);
mainMenu.SetActive(true);
Time.timeScale = 0f;
}
}
}
This script is working. When pressing the P button the game pause/continue. When pressing the ESCAPE key the game also pause but also back to the main menu by switching the gameobjects disable/enable.
Now let's say I pressed the escape key while playing the game and I'm back to the main menu now I want to start a new complete game but clicking the StartNewGame ui button.
The problem is that this time I don't want to just active the Game Data like I did before :
gameData.SetActive(true);
This time at least in my logic I want to destroy the existing Game Data and instantiate a new Game Data using a prefab I already have of the Game Data. This is my logic but I'm not sure how to do it. Or something like that.
The main goal is to be able to start over a new game each time clicking the StartNewGame ui button.