Downloaded Json File, not Working after Building the Game

Viewed 277

Good Day Community,

Im Working on a silly drinking game since a few weeks. Its all fine and dandy. Worked my way through all my ideas and got it done. I was pretty proud of my self. Now here´s the kicker. The game downloads a Json file from my Nextcloud using www in Unity. The Json Holds all the Game_Cards. It worked Really well in Unity, But after i build the game, Its just doing nothing. Im pretty Sure im missing something here. But i have no Clue how to Debug it. And to be frank, i think i have Workblindness on this one. I hope its a simple fix.

What i think is going on Maybe:

  • Download works Fine but Json file is saved to wrong or inaccesible Path
  • Download is not Working at all.

Card Path:

cardPath = Application.dataPath + "/Saves/cards.json";

Download Method

IEnumerator Cards()
    {
        UnityWebRequest www = new UnityWebRequest("https://my.link.wich/nobody/should/know");
        www.downloadHandler = new DownloadHandlerBuffer();
        yield return www.SendWebRequest();
        if (www.isNetworkError || www.isHttpError)
        {
            Debug.LogError(www.error);
        }
        else
        {
            string downloadedText = www.downloadHandler.text;
            File.WriteAllText(cardPath, downloadedText);
            ReadCards();
        }
    }

Reading Cards from Json

public void ReadCards()
    {
        string cardFile = File.ReadAllText(cardPath);
        cardDatabase = JsonUtility.FromJson<CardListObject>(cardFile);
    }

First time using StackOverflow an actually posting something. Be kind on me :D

Update

Got it Working! I had to create the Folder first.

cardPath = Application.persistentDataPath + "/Saves/cards.json";
if (!System.IO.Directory.Exists(Application.persistentDataPath + "/Saves"))
{
    System.IO.Directory.CreateDirectory(Application.persistentDataPath + "/Saves");
}
1 Answers

In build, you need to use Application.persistentDataPath not Application.dataPath

UPD: My bad, you are reading only if downloading. So you can ignore next part.

You need to do something in your ReadCards method in case the file does not exists, because you can have a download error and file will not be created.

For example:

public void ReadCards()
    {
        if (!System.IO.File.Exists(cardPath) return;

        string cardFile = File.ReadAllText(cardPath);
        cardDatabase = JsonUtility.FromJson<CardListObject>(cardFile);
    }

Then your cardDatabase will stay with default values and you will not have a FileNotFoundException.

Related