I have written code with a singleton pattern made for saving the top score of my player. It works fine when running through the first iteration. But when I go into different scenes and come back to the 'game' scene, only the first half of the while loop I wrote activates. Here is my script.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class ScoreSaver : MonoBehaviour
{
public static ScoreSaver score;
private int scoreSpeed = 1;
// Start is called before the first frame update
public static int topScore;
public int currentScore = 0;
void Awake()
{
if (score == null)
{
DontDestroyOnLoad(gameObject);
score = this;
}
else if (score != this)
{
Destroy(gameObject);
}
StartCoroutine(ScoreCounter());
}
IEnumerator ScoreCounter()
{
while (SceneManager.GetActiveScene() == SceneManager.GetSceneByName("game"))
{
Debug.Log("New Score Counter while loop is called");
yield return new WaitForSeconds(.1f);
Debug.Log("New Score Counter seconds have been waited");
currentScore = scoreSpeed;
Debug.Log("New Score Counter Score: " currentScore);
}
Debug.Log("New Score Counter IEnumerator is called");
if (currentScore > topScore)
{
topScore = currentScore;
Debug.Log("New Score Counter Top Score: " currentScore);
}
currentScore = 0;
Debug.Log("New Score Counter Current Score post Rest: " currentScore);
}
// Update is called once per frame
void Update()
{
}
}
It calls up to the "yield return new WaitForSeconds(.1f);" line, but does not call past it. It also doesn't run the rest of the function until the scene ends. So I really have no idea what is going on. Does anyone have a solution?
CodePudding user response:
You are mixing up DontDestroyOnload
and the Singleton
pattern. Separate them into their own different code events. Like this:
void Awake()
{
// First do the DontDestroyOnLoad
DontDestroyOnLoad(gameObject);
// Now do the singleton pattern
if (score == null)
{
score = this;
}
else if (score != this)
{
Destroy(gameObject);
}
}
void Start() {
// Do your code reoutine in start not awake
StartCoroutine(ScoreCounter());
}