我撰寫了帶有單例模式的代碼,用于保存我的播放器的最高分。運行第一次迭代時它作業正常。但是當我進入不同的場景并回到“游戲”場景時,只有我撰寫的 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);” 線,但不叫過去。在場景結束之前,它也不會運行其余的功能。所以我真的不知道發生了什么。有沒有人有辦法解決嗎?
uj5u.com熱心網友回復:
你正在混淆DontDestroyOnload
和Singleton
模式。將它們分成各自不同的代碼事件。像這樣:
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());
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483846.html
上一篇:Unity腳本未附加到其他腳本
下一篇:日/夜回圈并跟蹤日子?