get_persistentDataPath can only be called from the main thread ?

Im getting this error:

ArgumentException: get_persistentDataPath 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.
levelClass…cctor ()
Rethrow as TypeInitializationException: An exception was thrown by the type initializer for levelClass

I made a scene where the player can create a level, and it saves ussing serialization to a file in the path “Application.persistentDataPath + “/” + filename” and everything works like a charm, but when i load the “Building a level scene” from the “Main menu scene”, i get this error. I’ve spend a couple of hours trying fix it and looking at forums but can’t find any solution. Is it simply impossible to use the “Application.persistentDataPath”-command outside the main scene or wtf am i doing wrong?

The code is avaiable here http://pastebin.com/n3NmuZnr

Perhaps i didn’t explain myself accurate enough. The script that catches the exception is linked above. The scene works PERFECTLY when i play it directly in Unity, but when i load the scene with Application.LoadLevel(“build load scene”) from another scene, i get the error/exception. What is wrong ?

Probably this line

public static DirectoryInfo dir = new DirectoryInfo(Application.persistentDataPath + "/");

You should assign that in a start or awake method.

Also, rather use ints in the for loops instead of the floats. It doesn’t make much sense to use floats when you need ints anyways.

10 Likes

that was it, thank you :slight_smile:

  • how do a mark an answer as the correct answer ?

This is the forum, so there isn’t any way to mark an answer as correct. But, if he answered your question correctly, you can always press the “like” button and give him some rep. It’s the only form of kudos that we have on the forum…

If I’m not mistaken, which I may be, he could’ve called this from a Coroutine as well, right? Not that you would want to do that, since the path never changes so a reference from Start() would be sufficient enough, but from what I understand about Coroutines is that they don’t run on the main thread.

He could have called it there, too, just like in any other method which is (easily said) run in Awake or later.
As far as i know, coroutines run in the main thread as well, they’re just executed somewhere between Update and LateUpdate, but as you already mentioned, it’s not something that he’d need here.

Thanks Suddoha its work…

1 Like