我正在创建一个程序,在我的Unity项目构建完成后读取外部文本文件。调试日志可以完美地读取外部文件并发回我的文本或检测何时没有文件 - 我唯一的问题是将txt变量转换为GUI标签?我想知道为什么没有正确传递String变量,因为它只显示任何内容。任何帮助将不胜感激。
void Start () {
StreamReader reader = null;
FileInfo theSourceFile = null;
theSourceFile = new FileInfo (Application.dataPath + "/puzzles.txt");
if ( theSourceFile != null && theSourceFile.Exists )
reader = theSourceFile.OpenText();
if ( reader == null )
{
Debug.Log("puzzles.txt not found or not readable");
}
else
{
// Read each line from the file
while ((txt = reader.ReadLine()) != null)
Debug.Log("-->" + txt);
}
}
void OnGUI()
{
GUI.contentColor = Color.red;
GUI.Label(new Rect(500, 300, 400, 400), txt );
}
答案 0 :(得分:0)
我认为您误解了上面的代码是如何工作的。看起来您希望上面的代码显示文本文件的行,直到它完全读取为止,但Start()
方法在调用OnGUI()
方法之前完成。
表示txt = reader.ReadLine()
的最后一次调用为空,因此OnGUI
不显示任何内容。
如果你想显示上面的文字,我建议添加另一个变量并将字符串内容放入辅助变量(txt
,在这种情况下不要求成为类变量。)
使用StringBuilder
:
String txt;
completeText = "";
while ((txt = reader.ReadLine()) != null)
{
Debug.Log(....);
completeText += txt;
}
并使用OnGUI
方法:
GUI.Label(new Rect(500, 300, 400, 400), completeText );
如果你想以任何理由单独显示每一行,我建议你使用一个在每个ReadLine
之间有延迟的协程。