AZSWQ
AZSWQ

Reputation: 319

json load not working in build but works in unity editor

When I build on Android my json files seems to not load because I dont see data. in unity editor play it works fine. I'm struggling with something thats working on PC but not on Android. Just a path difference I guess but its not easy for a beginner.

here is my code TRY 1:

public static JsonData LoadFile(string path)
{
    var fileContents = File.ReadAllText(path);
    var data = JsonMapper.ToObject(fileContents);
    return data;
}

public void QuestionLoader()
{
    // Load the Json file and store its contents in a 'JsonData' variable
    var data = LoadFile(Application.dataPath + "/Resources/json/level1.json");

And Here is my try 2 - Based on Unity Manual - https://docs.unity3d.com/Manual/StreamingAssets.html:

   public static JsonData LoadFile(string path)
{

    var www = new WWW(path);
    return www.text;

    //var fileContents = File.ReadAllText(path);
   // var data = JsonMapper.ToObject(fileContents);
   // return data;
}

public void QuestionLoader()
{
    string path = "";
    // Load the Json file and store its contents 
    #if UNITY_ANDROID

    path = "jar:file://" + Application.dataPath + "!/assets/Levels/level1.json";

    #endif

    #if UNITY_EDITOR

    path = Application.dataPath + "/StreamingAssets/Levels/level1.json";

    #endif
    //
    var data = LoadFile(path);

Upvotes: 0

Views: 3210

Answers (1)

Programmer
Programmer

Reputation: 125455

If you want to load json that already exist in the project from any platform, you have two options:

1.Put the Json file in the Resources folder then use Resources.Load to read it as a TextAsset. See the end of this answer for example.

2.Make the json file an AssetBundle then use WWW.LoadFromCacheOrDownload to load it.


Any of these should work. Once you read the json file, you can copy it to the Application.persistentDataPath directly so that you will be able to modify it and save it if needed.

Upvotes: 1

Related Questions