【发布时间】:2017-07-04 17:03:01
【问题描述】:
所以我正在 Unity 中制作一个基本的 2D 平台游戏,我希望能够节省玩家完成每个关卡所需的时间,并在 UI 元素中显示最快的时间。我正在将时间写入文本文件(这工作正常),并将所有时间逐行读取到列表中,从那里我找到最低值等。但是,我的代码不起作用,它给了我以下当我从另一个脚本调用函数时出错。我是 C# 新手,因此非常感谢任何人能给我的帮助!
谢谢!
完整的错误信息
InvalidOperationException:由于对象的当前状态,操作无效
System.Linq.Enumerable.Iterate[Single,Single](IEnumerable1 source, Single initValue, System.Func3 选择器)
System.Linq.Enumerable.Min(IEnumerable`1 源)
SaveScores.ReadData (System.String LevelLoaded) (在 Assets/Scripts/Highscores/SaveScores.cs:73)
GameManager.Update () (在 Assets/Scripts/GameManager.cs:45)
代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System;
using System.Linq;
public class SaveScores : MonoBehaviour {
void Start()
{
//ReadData();
}
public static void WriteData(float time, string LevelLoaded)
{
try
{
//Debug.Log("Saving time");
StreamWriter sw = new StreamWriter(@"C:\Users\Theo\Documents\Unity Projects\V13\Platformer\Assets\Scripts\Highscores\Scores.txt", true);
sw.WriteLine(LevelLoaded + " " + time);
sw.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing final block");
}
}
public static void ReadData(string LevelLoaded)
{
List <float> timesLevel1 = new List<float>();
List <float> timesLevel2 = new List<float>();
List <float> timesLevel3 = new List<float>();
try
{
var lines = File.ReadAllLines(@"C:\Users\Theo\Documents\Unity Projects\V13\Platformer\Assets\Scripts\Highscores\Scores.txt");
foreach (var line in lines)
{
if (line.Contains("Level1"))
{
timesLevel1.Add(Convert.ToSingle(line));
}
else if (line.Contains("Level2"))
{
timesLevel2.Add(Convert.ToSingle(line));
}
else if (line.Contains("Level3"))
{
timesLevel3.Add(Convert.ToSingle(line));
}
}
}
catch (Exception e)
{
Console.WriteLine("Exception: " + e.Message);
}
finally
{
Console.WriteLine("Executing final block");
}
switch (LevelLoaded)
{
case "Level1":
UIManager.lowestTime = timesLevel1.Min();
break;
case "Level2":
UIManager.lowestTime = timesLevel2.Min();
break;
case "Level3":
UIManager.lowestTime = timesLevel3.Min();
break;
}
}
}
【问题讨论】: