C# Unity显示最佳时间
我是Unity的初学者,正在寻求帮助。我做了一个简单的游戏,你可以尝试尽快完成几个关卡。我有一个计时器脚本,我想用它在主菜单的表格中保存最佳时间。我已经用playerprefs研究了一些解决方案,但我仍然有点迷茫,如果有人能指导我解决这个问题,我将非常感激 计时器脚本:C# Unity显示最佳时间,c#,unity3d,timer,C#,Unity3d,Timer,我是Unity的初学者,正在寻求帮助。我做了一个简单的游戏,你可以尝试尽快完成几个关卡。我有一个计时器脚本,我想用它在主菜单的表格中保存最佳时间。我已经用playerprefs研究了一些解决方案,但我仍然有点迷茫,如果有人能指导我解决这个问题,我将非常感激 计时器脚本: public class Timercontroller : MonoBehaviour { }您是否只是在寻找节省计时器的建议? 因此,假设您的代码是正确的,并且您只是希望节省/加载时间,我将执行以下操作: List<
public class Timercontroller : MonoBehaviour
{
}您是否只是在寻找节省计时器的建议? 因此,假设您的代码是正确的,并且您只是希望节省/加载时间,我将执行以下操作:
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]);
}
}
List bestTimes=new List();
int totalScores=5;//要保存的总次数
///
///在唤醒中调用此命令以加载数据。
///它检查您是否有任何保存的时间,如果有,则将其添加到列表中。
///
公共无效加载时间(){
对于(int i=0;ib.CompareTo(a));
存储时间();
}否则{
for(int i=0;i
我还没有机会测试这个,但它似乎对我有用
要更新highscores列表中的文本,假设它们都是文本对象,我将创建一个新脚本,将其添加到每个文本对象,并将以下内容添加到代码中:
private void Awake(){
int index = transform.SetSiblingIndex();
Text theText = GetComponent<Text>().text;
if (PlayerPrefs.HasKey(index)) {
theText = PlayerPrefs.GetFloat(index).ToString();
}else{
theText = "0";
}
}
private void Awake(){
int index=transform.SetSiblingIndex();
Text theText=GetComponent().Text;
if(PlayerPrefs.HasKey(索引)){
text=PlayerPrefs.GetFloat(index.ToString();
}否则{
theText=“0”;
}
}
我没有设置上面的文本格式,但这是一个小小的调整。非常感谢,这似乎有效,目前为止没有出现任何错误。但我如何才能真正让分数显示在主菜单中的高分列表上呢?我更新了回复,加入了我的建议。
private void Awake(){
int index = transform.SetSiblingIndex();
Text theText = GetComponent<Text>().text;
if (PlayerPrefs.HasKey(index)) {
theText = PlayerPrefs.GetFloat(index).ToString();
}else{
theText = "0";
}
}