I'm trying to make a readable book in Unity. I have a folder with .txt files for pages. I want to put the text from these files on a Text UI element. The idea is that the script finds the number of files, and based on that populates an array of strings. Then the script finds out on which UI Text element to put the text. I will have a button that changes bookSectionOne and bookSectionTwo and restarts the script, so that the new page gets loaded.
Unity is giving me an error:
NullReferenceException: Object reference not set to an instance of an object (wrapper stelemref) object:stelemref (object,intptr,object) BookTextAppender.Start () (at 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]);
}
}
}
}
The line that is giving problems:
contents[i] = File.ReadAllText(bookResourcesPath + txtFile);