Quantcast
Channel: Questions in topic: "playerprefs"
Viewing all articles
Browse latest Browse all 1333

How to create a main menu with singleton pattern?

$
0
0
Hello everyone, I am new both to this forum and Unity, so please bare with me, my understanding of this might not be the best. I am using a game manager to manage my game data (lives, score, position in player prefs) and game scenes. My GameManagerObject is in the game scene and I created a singleton pattern in awake method of game manager script. In order to switch to game over or win scene after the player dies or wins, I am using OnSceneLoaded method, and also enabling it in Awake. Now my question is, how do I implement a main menu, or create a retry button on game over scene which will lead to my game scene again, as the singleton won't let me execute the start method the second time? Basically, I believe because of singleton, when my game is run directly from the scene everything runs accordingly, but when I load the game through another scene I am getting an error saying that the GameObjectManager has been destroyed. I also had an issue where the playerPrefs "weren't loading" when starting the game from another scene (e.g. player lives were null), and now I managed to fix it but they are still not saving and loading. This a part of my code. Disclaimer, I am supposed to use a singleton so I'm mainly searching for solutions including its use.. Thanks private void Awake() { //singleton if (_instance == null) { _instance = this; } else if (_instance != this) { Destroy(this.gameObject); } SceneManager.sceneLoaded += OnSceneLoaded; //for gameover DontDestroyOnLoad(this.gameObject); } void Start() { //there's more but basically loading and displaying data GetComponent().LoadData(); } And these are my GameOver and Win scenes. void OnSceneLoaded(Scene scene, LoadSceneMode mode) { if (scene.name == "GameOver" || scene.name == "Win") { Text scoretext = GameObject.Find("Scoretext").GetComponent(); scoretext.text = "score: " + GameData.GameScore.ToString(); if (GameData.GameScore > GameData.HighScore) GameData.HighScore = GameData.GameScore; Text highscoretext = GameObject.Find("Highscore").GetComponent(); highscoretext.text = "highest score: " + GameData.HighScore.ToString(); //also displaying and saving newly set data }

Viewing all articles
Browse latest Browse all 1333

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>