我写了一个简单的计时器脚本,在计时器到达 0 后加载一个新场景。但它会不断加载场景,而不是一次不允许播放它加载的场景。我只需要它加载一次场景。
using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using UnityEngine.SceneManagement;
public class Timer : MonoBehaviour
{
public float timelimit;
public Text text;
public void ChangeScene(int changeTheScene)
{
SceneManager.LoadScene(changeTheScene);
}
void Update()
{
timelimit -= Time.deltaTime;
text.text = "TimerText:" + Mathf.Round(timelimit);
if (timelimit < 0)
{
timelimit = 0;
SceneManager.LoadScene(1);
}
}
}
最佳答案
注意:您描述的代码不会导致您描述的问题。我看到两种可能性:
- 您新加载的场景中有相同的组件,重复加载场景
- 您实际上是附加地加载场景,因此该组件在加载后继续运行。
假设是后者,如果您按照代码执行,您会看到您的 if
语句有一个条件,一旦达到时间限制,该条件将始终为真:
每帧你从 timelimit
中减去一个数字。然后,如果 timelimit
现在小于零,则将 timelimit
设置为零并加载场景。
如果您在前一帧中将时间限制设置为零,然后减去一个数字,它将始终小于零:您将始终在每个后续帧上再次加载场景。
请尝试使用 bool 变量来跟踪您是否已加载场景。或者,在加载场景后立即销毁组件,以便您的代码停止运行。
如果问题实际上是你的新场景中也有这个组件......考虑删除它! :-)
编辑:
Try instead using a boolean variable to track whether you've loaded the scene or not.
public class Timer : MonoBehaviour
{
public float timelimit;
public Text text;
static bool loadedScene = false;
public void ChangeScene(int changeTheScene)
{
//SceneManager.LoadScene(changeTheScene);
}
void Update()
{
//Exit if we have already loaded scene
if (loadedScene)
{
//Destroy Timer Text
Destroy(text.gameObject);
//Destroy this Timer GameObject and Script
Destroy(gameObject);
return;
}
timelimit -= Time.deltaTime;
text.text = "TimerText:" + Mathf.Round(timelimit);
if (timelimit < 0)
{
timelimit = 0;
loadedScene = true; //We have loaded Scene so mark it true
SceneManager.LoadScene(1);
}
}
}
关于c# - 计时器不断加载场景而不是一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41667841/