- Home /
Error: get_dataPath can only be called from the main thread
I'm getting this error:
get_dataPath can only be called from the main thread. Constructors and field initializers will be executed from the loading thread when loading a scene. Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.
All I'm trying to do is load a text file from the resources folder of the project. Originally I was just setting the filepath with a string and loading from that but it would not work when publishing to the web.
Code is as follows:
TextAsset infoFile;
public SearchField searchfield;
public void Update()
{
if (searchfield.Confirm == true)
{
infoFile = (TextAsset)Resources.Load(searchfield.ToString(), typeof(TextAsset));
string[] allcontents = File.ReadAllLines(infoFile.text);
contents = ConvertStringArrayToStringJoin(allcontents);
}
}
Answer by PAHeartBeat · Mar 15, 2013 at 05:36 PM
TextAsset infoFile;
public SearchField searchfield;
public void Update(){
if (searchfield.Confirm == true) {
infoFile = (TextAsset)Resources.Load(searchfield.ToString(), typeof(TextAsset));
string contents = infoFile.text;
string[] allLines = contents.Split('\n');
}
}
Code gives above can read your text file from Resources Folder. if you don't want array of all lines in seprate field just comment line in which I use Split function.
Doesnt seem to work. I tried passing 'contents' to the GUI and it doesnt show the text and reports a null reference exception
Hi Can you provide your exact code which you writes in GUI function..
and I want to clear a thing, when you use Resources.Load() function it's not counting ext of the file. like file is Data.txt in you need to use just Data in your function.
null reference means code line
infoFile = (TextAsset)Resources.Load(searchfield.ToString(), typeof(TextAsset));
can't find any files with name which return by searchfield.ToString()
in resources folder please check the file name which you want to read from resources folder
Hi Please change the code as i gave bellow
string allcontents
public void Update() {
if (searchfield.Confirm == true){
string path = searchfield.Search";
infoFile = (TextAsset)Resources.Load(path.ToString(), typeof(TextAsset));
allcontents = infoFile.text;
contents = allcontents.Split('\n');
}
}
and GUI code:
GUI.Label(new Rect(posX,posY,width,screenheight), allcontents, "label");
or
GUI.Label(new Rect(posX,posY,width,screenheight), string.Join('\n', contents), "label");
You are welcome bro.. and it's my pleasure to help you. Please $$anonymous$$ark question is Accepted so other new-bee developer also use it....
thanks a lot for your valuable time...