协程只有一半被调用

Only Half of CoRoutine Being called

我编写了带有单例模式的代码,用于保存我的玩家的最高分。当 运行ning 通过第一次迭代时,它工作正常。但是当我进入不同的场景并回到 'game' 场景时,只有我编写的 while 循环的前半部分激活。这是我的脚本。


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()
    {
        
    }
}


它调用了“yield return new WaitForSeconds(.1f);”行,但不会呼叫过去。在场景结束之前,它也不会 运行 函数的其余部分。所以我真的不知道发生了什么。有人有解决办法吗?

您混淆了 DontDestroyOnloadSingleton 模式。将它们分成各自不同的代码事件。像这样:

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());
}