c# - 在 Unity 中重新加载场景后 StreamReader 无法正常工作

标签 c# unity3d streamreader

我有一个流阅读器,我用它来将数据解析到程序中。当我第一次从主菜单打开场景时,流读取器在解析数据时工作正常(我在代码片段中省略了解析,因为代码很长)。第一次运行时输出到屏幕的 text.text 是 G。如果我加载回主菜单,然后回到这个场景,但是 text.text 输出是我的代码读取文本的文本文档的第一行.text = line,我想找出原因。 sr.Close() 不是关闭流阅读器的正确方法吗?或者文件是否仍然以某种方式打开?

void Start () {
    text.text = "A";
    trimAndPlaceDataSets = GetComponent<TrimAndPlaceDataSets> ();
    text.text = "B";
    string AthenaData = Application.streamingAssetsPath + "/Athena.txt";
    text.text = "C";
    PopulateAthenaData(AthenaData);
}

void PopulateAthenaData(string s){
    text.text = "D";
    using (StreamReader sr = new StreamReader(s)) {
        text.text = "E";
        string line = sr.ReadLine();
        text.text = line;
        while (line != null) {
            //Do Stuf
            sr.ReadLine();
        }
        sr.Close();
        text.text = "G";
    }
}

这就是我加载场景的方式

public void LoadPressed() {
        scenesDropdown.gameObject.SetActive(false);
        loadButton.SetActive(false);
        SceneManager.LoadScene(scenesArray[scenesDropdown.value]);
    }

最佳答案

使用正确的方式为你关闭流,这是因为 StreamReader 类已经实现了接口(interface) IDisposable,这允许使用 using 语句,它在范围结束后自动调用 SreamReader 中的 Dispose 方法,并在该方法中清除资源并关闭打开文件,如果需要,最后一步称为垃圾收集器

using (StreamReader sr = new StreamReader(s))
{
    //do stuff with stream reader
    //sr.Close();
}

关于c# - 在 Unity 中重新加载场景后 StreamReader 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47228733/

相关文章:

c# - 使用表单保存到文本文件

c# - StreamReader 参数NullException

c# - 为什么 CaSTLe Windsor 拦截器会破坏 C# 动态对象上方法的运行时绑定(bind)?

c# - 获取文件夹中的下一个文件

c# - 在 C#/.NET 中处理基督之前日期的(最佳)方法是什么?

c# - 在基于 Unity 的 Roguelike 中调整代码执行

c# - 获取成像设备

c# - 如何更改通过 PrefabUtility.InstantiatePrefab 实例化的 GameObject 的父对象?

ios - Facebook API 7.5.0 崩溃统一 OnInitComplete()

c# - 为多个 XmlReader.Read() 用法重置 StreamReader