我正在努力用Unity制作一本可读的书。我有一个文件夹,里面有用于页面的.txt文件。我想把这些文件中的文本放在一个文本UI元素上。其思想是,脚本查找文件的数量,并在此基础上填充字符串数组。然后脚本会找出要将文本放在哪个UIText元素上。我将有一个按钮来更改bookSectionOne和bookSectionTwo并重新启动脚本,以便加载新页面。
Unity给了我一个错误:
NullReferenceException:对象引用未设置为object(包装器stelemref(object:stelemref(object,intptr,object(BookTextAppender.Start(((位于Assets/Scripts/Book/BookTextAppender.cs:35(
using UnityEngine;
using System.IO;
using UnityEngine.UI;
public class BookTextAppender : MonoBehaviour
{
public int bookSectionOne;
public int bookSectionTwo;
public Text Text1;
public Text Text2;
public string txtFile;
string bookResourcesPath;
int fileNumber;
string[] contents;
// Use this for initialization
void Start ()
{
bookResourcesPath = Application.dataPath + "/Resources/BookText/";
print("Directory: " + bookResourcesPath);
fileNumber = Directory.GetFiles(bookResourcesPath).Length;
fileNumber /= 2;
print("FileNum: " + fileNumber);
for (int i = 1; i <= fileNumber; i++)
{
txtFile = txtFile + i.ToString() + ".txt";
print("FileName: " + txtFile);
print("Path:" + bookResourcesPath + txtFile);
contents[i] = File.ReadAllText(bookResourcesPath + txtFile);
print("Content" + i + ": " + contents[i]);
if (bookSectionTwo == i)
{
Text2.text = contents[i];
print("Text2: " + contents[i]);
}
else if (bookSectionOne == i)
{
Text1.text = contents[i];
print("Text1: " + contents[i]);
}
}
}
}
出现问题的线路:
contents[i] = File.ReadAllText(bookResourcesPath + txtFile);
您需要初始化contents
。您正试图引用尚未分配的数组。
contents = new string[20];