Unity展示了最好的时光



我是Unity的初学者,正在寻求一些帮助。我做了一个简单的游戏,你可以尽可能快地完成几个关卡。我有一个计时器脚本,我想用它来保存主菜单上表格中的最佳时间。我已经和球员们讨论过一些解决方案,但我仍然有点不知所措,如果有人能指导我度过难关,我将非常感激。

计时器脚本:

public class Timercontroller : MonoBehaviour

public Text timeCounter;
public TimeSpan timePlaying;
public bool timerGoing;
public float elapsedTime;

public void Awake()
{
DontDestroyOnLoad(this.gameObject);
}

void Start()
{
timeCounter.text = "Time: 00:00.00";
timerGoing = false;
BeginTimer();

}
public void BeginTimer()
{
timerGoing = true;
elapsedTime = 0f;
StartCoroutine(UpdateTimer());
}
public void EndTimer()
{
timerGoing = false;
}
public IEnumerator UpdateTimer()
{
while (timerGoing)
{
elapsedTime += Time.deltaTime;
timePlaying = TimeSpan.FromSeconds(elapsedTime);
string timePlayingString = "Time: " + timePlaying.ToString("mm':'ss'.'ff");
timeCounter.text = timePlayingString;
yield return null;
}
}
void Update()
{
int currentSceneIndex = SceneManager.GetActiveScene().buildIndex;
if (currentSceneIndex == 5) {
EndTimer();
}

}

}

您只是在寻找关于保存计时器的建议吗?因此,假设你的代码是正确的,并且你只是想节省/加载时间,我会做如下操作:

List<float> bestTimes = new List<float>();
int totalScores = 5; // the total times you want to save

/// <summary>
///  Call this in Awake to load in your data.
///  It checks to see if you have any saved times and adds them to the list if you do.
/// </summary>
public void LoadTimes() {
for (int i = 0; i < totalScores; i++) {
string key = "time" + i;
if (PlayerPrefs.HasKey(key)) {
bestTimes.Add(PlayerPrefs.GetFloat(key));
}
}
}
/// <summary>
/// Call this from your EndTimer method. 
/// This will check and see if the time just created is a "best time".
/// </summary>
public void CheckTime(float time) {
// if there are not enough scores in the list, go ahead and add it
if (bestTimes.Count < totalScores) {
bestTimes.Add(time);
// make sure the times are in order from highest to lowest
bestTimes.Sort((a, b) => b.CompareTo(a));
SaveTimes();
} else {
for (int i = 0; i < bestTimes.Count; i++) {
// if the time is smaller, insert it
if (time < bestTimes[i]) {
bestTimes.Insert(i, time);
// remove the last item in the list
bestTimes.RemoveAt(bestTimes.Count - 1);
SaveTimes();
break;
}
}
}
}
/// <summary>
/// This is called from CheckTime().
/// It saves the times to PlayerPrefs.
/// </summary>
public void SaveTimes() {
for (int i = 0; i < bestTimes.Count; i++) {
string key = "time" + i;
PlayerPrefs.SetFloat(key, bestTimes[i]);
}
}

我还没有机会测试这个,但它似乎对我有用。

为了更新高核心列表上的文本,假设它们都是文本对象,我会创建一个新脚本,将其添加到每个文本对象中,并将以下内容添加到代码中:

private void Awake(){
int index = transform.SetSiblingIndex();
Text theText = GetComponent<Text>().text;
if (PlayerPrefs.HasKey(index)) {
theText = PlayerPrefs.GetFloat(index).ToString();
}else{
theText = "0";
}
}

我没有格式化上面的文本,但这是一个小的调整。

相关内容

  • 没有找到相关文章

最新更新