I am confused with a NullReferenceException error. I have a script that populates a label from Resource .txt files. The script runs on different scenes and modifies the text as one chooses a collider. It works flawless the first time you open the scene but if you go back to the main menu and reenters the scene or if you move to a different scene, the error appears. Someone at unity forum suggested that I used Object.DontDestroyOnLoad but seems unlikely to solve my problem
void ChangeFeaturedText(string filename)
{
//Load text data from resources
TextAsset toothdata
= (TextAsset
)Resources
.Load(filename,
typeof(TextAsset
)); reader
= new StringReader
(toothdata
.text);
//confirm if textdata is valid and read it
if ( reader == null )
{
Debug.Log(filename+".txt not found or not readable");
}
else
{
// Read each line from the fil+string txt;
string txt;
longtext="";
while ( (txt=reader.ReadLine()) != null)
{
longtext += txt;
}
reader.Close();
UILabel label = NGUITools.FindInParents<UILabel>(labeltarget);
Debug.Log (filename+".txt target found");
label.text=longtext;// line where error appears: NullReferenceException: Object reference not set to an instance of an object
//SelectFeature.ChangeFeaturedText (System.String filename) (at Assets/Scripts/SelectFeature.cs:106)
Resources.UnloadAsset (toothdata);
}
}
How can I use the same script on different scenes with the ability to move from one to another?
Many thanks