此代码允许读取.txt文件并将其放入GUI标签中,然后显示为屏幕文本。到目前为止,txt文件被放入List中,然后foreach
然后分配变量。但是,我的问题是文本文件在每个标签中出现在一起而不是单独出现,我想知道如何做到这一点?
powersupply.txt用于powersupply模型,puzzles.txt用于cdrw模型。任何帮助是极大的赞赏。
using UnityEngine;
using System.Collections;
using System.IO;
// To use List
using System.Collections.Generic;
public class OnClick : MonoBehaviour
{
string cdrw = "CD-RW";
string powerSupply = "Power Supply";
public string txt;
public static string completeText = "";
public GameObject cdrwModel;
public GameObject powerSupplyModel;
public StreamReader reader = null;
public FileInfo theSourceFile = null
private static List<string> _allFiles = new List<string>();
public void Start()
{
theSourceFile = new FileInfo(Application.dataPath + "/puzzles.txt");
ProcessFile(theSourceFile);
theSourceFile = new FileInfo(Application.dataPath + "/powersupply.txt");
ProcessFile(theSourceFile);
}
private void ProcessFile(FileInfo file)
{
if (file != null && file.Exists)
reader = file.OpenText();
if (reader == null)
{
Debug.Log("puzzles.txt not found or not readable");
}
else
{
while ((txt = reader.ReadLine()) != null)
{
Debug.Log("-->" + txt);
completeText += txt + "\n";
}
_allFiles.Add(completeText);
}
}
public void OnGUI()
{
if ((isClicked) && (cdrwModel))
{
GUI.Label(new Rect(15, 35, 400, 400), "Press <TAB> for more information");
if (Input.GetKey(KeyCode.Tab))
{
foreach (var file in _allFiles)
{
GUI.contentColor = Color.red;
GUI.Label(new Rect(1000, 50, 400, 400), file);
}
}
}
else if ((isClicked) && (powerSupplyModel))
{
GUI.Label(new Rect(15, 35, 400, 400), "Press <TAB> for more information");
if (Input.GetKey(KeyCode.Tab))
{
foreach (var file in _allFiles)
{
GUI.contentColor = Color.red;
GUI.Label(new Rect(1000, 50, 400, 400), file);
}
}
}
}
}
答案 0 :(得分:0)
您正在向_allFiles添加对同一个completeText字符串的2个引用,添加第一个实例后所做的任何更改都将在该列表的条目中看到,因为它是对同一对象的引用。每次要添加不同的文本时,都需要创建一个新实例。您可以将completeText作为ProcessFile的局部变量。