Unity not saving to Json file anymore?

Recommended Posts

Hey Community,

I have a question about C# and Unity.

For my options menu I wrote a script with C#, that worked fine for a while.

My problem is to let unity write a .Json file into the LocalLow folder. At first everything went fine and there occurred no errors, but now the file is only generated completely empty. I didn't change anything in the script and Visual Studio doesn't show any errors to me, so I have no clue what is wrong.

As I'm only a beginner, I hope anyone of you guys can find what I messed up and give me some advices.

Code for the GameSettings

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameSettings
{
    //all variables assigned to their class. 
    public bool fullscreen;
    public float musicvolume;
    public float audiovolume;
    public int difficulty;
    public bool subtitles;
    public int Language;
    public int vsync;
    public int texturequality;
    public int resolution;
    public float gamma;
    public int antialiasing;
    public bool autosave;
}

Code for the SettingManager

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;

public class SettingManager : MonoBehaviour
{
    //all variables assigned to their class. 
    public Slider musicvolumeslider;
    public Toggle fullscreenToggle;
    public Slider audiovolumeSlider;
    public Dropdown difficultyDropdown;
    public Toggle subtitlesToggle;
    public Dropdown languageDropdown;
    public Dropdown vsyncDropdown;
    public Dropdown texturequalityDropdown;
    public Slider gammaSlider;
    public Dropdown antialiasingDropdown;
    public Toggle autosaveToggle;
    public Dropdown resolutionDropdown;
    public Button closeButton;

    public AudioSource musicSource;
    public Resolution[] resolutions;
    public GameSettings gameSettings;

    void OnEnable()
    {
        DontDestroyOnLoad(gameObject);
        musicvolumeslider.onValueChanged.AddListener(delegate { OnMusicVolumeChange(); });
        fullscreenToggle.onValueChanged.AddListener(delegate { OnFullscreenToggle(); });
        audiovolumeSlider.onValueChanged.AddListener(delegate { OnAudioVolumeChange(); });
        difficultyDropdown.onValueChanged.AddListener(delegate { OnDifficultyChange(); });
        subtitlesToggle.onValueChanged.AddListener(delegate { OnSubtitlesChange(); });
        languageDropdown.onValueChanged.AddListener(delegate { OnLanguageChange(); });
        vsyncDropdown.onValueChanged.AddListener(delegate { OnVSyncChange(); });
        texturequalityDropdown.onValueChanged.AddListener(delegate { OnTextureQualityChange(); });
        gammaSlider.onValueChanged.AddListener(delegate { OnGammaChange(); });
        autosaveToggle.onValueChanged.AddListener(delegate { OnAutosaveToggle(); });
        antialiasingDropdown.onValueChanged.AddListener(delegate { OnAAChange(); });
        resolutionDropdown.onValueChanged.AddListener(delegate { OnResolutionChange(); });
        closeButton.onClick.AddListener(delegate { OnCloseButtonClick(); });

        musicSource = GameObject.FindGameObjectWithTag("music").GetComponent<AudioSource>();
        gameSettings = new GameSettings();
        resolutions = Screen.resolutions;
        foreach (Resolution resolution in resolutions)
        {
            resolutionDropdown.options.Add(new Dropdown.OptionData(resolution.ToString()));
        }
        LoadSettings();
    }

    public void OnMusicVolumeChange()
    {
        musicSource.volume = gameSettings.musicvolume = musicvolumeslider.value;
    }
    public void OnResolutionChange()
    {
        Screen.SetResolution(resolutions[resolutionDropdown.value].width, resolutions[resolutionDropdown.value].height, Screen.fullScreen);
        gameSettings.resolution = resolutionDropdown.value;
    }
    public void OnFullscreenToggle()
    {
        gameSettings.fullscreen = Screen.fullScreen = fullscreenToggle.isOn;
    }
    public void OnAudioVolumeChange()
    {
        AudioListener.volume = gameSettings.audiovolume = audiovolumeSlider.value;
    }
    public void OnDifficultyChange()
    {
        //Not Implemented Yet
    }
    public void OnSubtitlesChange()
    {
        //Not Implemented Yet
    }
    public void OnLanguageChange()
    {
        if (languageDropdown.value == 0)
            LocalizationService.Instance.Localization = "English";
        if (languageDropdown.value == 1)
            LocalizationService.Instance.Localization = "German";
        if (languageDropdown.value == 2)
            LocalizationService.Instance.Localization = "French";
        if (languageDropdown.value == 3)
            LocalizationService.Instance.Localization = "Russian";
        if (languageDropdown.value == 4)
            LocalizationService.Instance.Localization = "Italian";
        if (languageDropdown.value == 5)
            LocalizationService.Instance.Localization = "Chinese";
    }
    public void OnVSyncChange()
    {
        QualitySettings.vSyncCount = gameSettings.vsync = vsyncDropdown.value;
    }
    public void OnTextureQualityChange()
    {
        QualitySettings.masterTextureLimit = gameSettings.texturequality = texturequalityDropdown.value;
    }
    public void OnGammaChange()
    {
        //Not Implemented Yet
    }
    public void OnAAChange()
    {
        QualitySettings.antiAliasing = (int)Mathf.Pow(2, antialiasingDropdown.value);
        gameSettings.antialiasing = antialiasingDropdown.value;
    }
    public void OnAutosaveToggle()
    {
        //Not Implemented Yet
    }
    public void OnCloseButtonClick()
    {
        SaveSettings();
    }
    public void SaveSettings()
    {
        string jsonData = JsonUtility.ToJson(gameSettings, true);
        File.WriteAllText(Application.persistentDataPath + "/gamesettings.json", jsonData);
    }
    public void LoadSettings()
    {
        gameSettings = JsonUtility.FromJson<GameSettings>(File.ReadAllText(Application.persistentDataPath + "/gamesettings.json"));
        audiovolumeSlider.value = gameSettings.audiovolume;
        antialiasingDropdown.value = gameSettings.antialiasing;
        gammaSlider.value = gameSettings.gamma;
        texturequalityDropdown.value = gameSettings.texturequality;
        vsyncDropdown.value = gameSettings.vsync;
        languageDropdown.value = gameSettings.Language;
        subtitlesToggle.isOn = gameSettings.subtitles;
        Screen.fullScreen = gameSettings.fullscreen;
        difficultyDropdown.value = gameSettings.difficulty;
        resolutionDropdown.value = gameSettings.resolution;
        autosaveToggle.isOn = gameSettings.autosave;
        musicvolumeslider.value = gameSettings.musicvolume;

        resolutionDropdown.RefreshShownValue();

    }
}

Hoping for fast help,

SanguineTunic

Share this post


Link to post
Share on other sites

Generally, it's best to only post the code that you think is relevant. In this case, that's probably only these lines:

        string jsonData = JsonUtility.ToJson(gameSettings, true);
        File.WriteAllText(Application.persistentDataPath + "/gamesettings.json", jsonData);

First, you should use the Visual Studio debugger, or maybe a Debug.Log call, to see if anything is going into that jsonData string. If not, it implies that your GameSettings class isn't serialisable. The docs forToJson say that it "it must be a MonoBehaviour, ScriptableObject, or plain class/struct with the Serializable attribute applied. " I don't see that as being true in your case. You probably need to add that Serializable attribute.

 

Share this post


Link to post
Share on other sites

Hmm, I tested the save section with a debug.Log and it clearly is called when clicking on the apply button.

I don't get what is wrong. It worked like a charm at first! So, thanks for your fast reply. I hope there is a solution to my problem anywhere, as what you mentioned about the missing Serializable attribute didn't help.

 

Share this post


Link to post
Share on other sites

The point of my logging suggest line isn't to see whether it's being called - the point is to log the content of jsonData and see what is being stored in there.

And if you've added the Serializable property, show us what you have now, so that someone might be able to test it themselves.

Share this post


Link to post
Share on other sites

Oh, Sorry. Misunderstood that. This is what comes out when I log the content:

<string jsonData = JsonUtility.ToJson(gameSettings, true)>
UnityEngine.Debug:Log(Object)
SettingManager:SaveSettings() (at Assets/Menu/Main Scripts/SettingManager.cs:130)
SettingManager:OnCloseButtonClick() (at Assets/Menu/Main Scripts/SettingManager.cs:126)
SettingManager:<OnEnable>m__C() (at Assets/Menu/Main Scripts/SettingManager.cs:43)
UnityEngine.EventSystems.EventSystem:Update()

 

Share this post


Link to post
Share on other sites

I now found one possible cause, after starting the game in built mode with development mode active.

When saving it says:

Quote

IsolatedStorageException: Could not find part of the path "C:\users\Sanguine\AppData\LocalLow\SanguineTunic\ProjectName\gamesettings.json"

I don't get why... The path is exactly the same as it should be.

Maybe one of you can find the mistake I made.

Share this post


Link to post
Share on other sites

I don't know what you've done with that log line, but you should be able to print the actual content of the string (whereas what you've got there is the line of code, strangely) and see if there's actually any JSON in it. Better still, put a breakpoint in the debugger on that line, and use the debugger to see what is in there.

No idea about the IsolatedStorageException - that might be something worth asking on the Unity forums about.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Forum Statistics

    • Total Topics
      628682
    • Total Posts
      2984214
  • Similar Content

    • By hiya83
      Hi,
      Does anyone have suggestions on multi-gpu (cross adapter) debugging in vs2015 for dx12? It seems this is not supported (error codes returned when gpu debugging inside VS) in vs2015. Any idea if this is supported in vs2017? 
      Thanks
    • By Ethan Webb
      Hello,
      So I'm making Galaga in Visual Basic for a class project, I'm stuck to Visual Basic (sigh) and so far I have my ship moving back and forth and shooting and when it shoots and the laser hits a PictureBox the PictureBox explodes, but now I'm to the point were I need invaders/enemies to fly in and line up in there positions. I'm completely stuck on how to make 5 or so ships fly in a set path and then go to a line.  If anyone has any advice on how to make them fly in a set path that would be great. 
      Thanks.
    • By glportal
      GlPortal is a free and open source first person 3D teleportation based puzzle game and platformer. But we have already integrated a physics engine and are planning for some physics based puzzles.
      We want to improve our Visual Studio support. Check out this project:
      https://github.com/kungfooman/glportal-vs
      You can chat with us on gitter https://gitter.im/GlPortal/glPortal
    • By GameDevCoder
      I have to learn DirectX for a course I am studying. This book https://www.amazon.co.uk/Introduction-3D-Game-Programming-Directx/dp/1936420228 I felt would be great for me to learn from.
      The trouble is the examples which are all offered here http://www.d3dcoder.net/d3d11.htm . They do not work for me. This is a known issue as there is a link on the examples page saying how to fix it. I'm having difficulty with doing this though. This is the page with the solution http://www.d3dcoder.net/Data/Book4/d3d11Win10.htm.
      The reason why this problem is happening, the book was released before Windows 10 was released. Now when the examples are run they need slight fixes in order for them to even work. I just can't get these examples working at all.
      Would anyone be able to help me get the examples working please. I am running Windows 10 also just to make this clear, so this is why the examples are experiencing the not so desired behaviour. I just wish they would work straight away but there seems to be issues with the examples from this book mainly because of it trying to run from a Windows 10 OS.
      On top of this, if anyone has any suggestions with how I can learn DirectX 11 i would be most grateful. Thanks very much. I really would like to get them examples working to though from the book I mentioned.
      Look forward to reading any replies this thread receives.
       
      GameDevCoder.


      PS - If anyone has noticed. I asked this about 1 year ago also but this was when I was dabbling in it. Now I am actually needing to produce some stuff with DirectX so I have to get my head round this now. I felt at the time that I sort of understood what was being written to me in response to my thread back then. I had always been a little unsure though of being absolutely sure of what was happening with these troublesome examples. So I am really just trying to get to the bottom of this now. If anyone can help me work these examples out so I can see them working then hopefully I can learn DirectX 11 from them.
       
      *SOLUTION* - I was able to get the examples running thanks to the gamedev.net community. Great work guys. I'm so please now that I can learn from this book now I have the examples running.
      https://www.gamedev.net/forums/topic/693437-i-need-to-learn-directx-the-examples-for-introduction-to-3d-programming-with-directx-11-by-frank-d-luna-does-not-work-can-anyone-help-me/?do=findComment&comment=5363013
    • By Sam Mason
      Hi all,
      I have written a nice(ish) looking game of solitaire in Windows Forms, using VB.NET and Visual Studio 2015. It allows the player to play the game, and if their score is in the top 10, it saves the username and score o a leaderboard (saved in a text file so it is non-volatile). My next goal is to let the user know if the hand they are dealt is playable, but I'm not sure on the most efficient way of achieving this. I'm working on time complexity over space complexity! It's a simple game to code, but not an easy one to find the solution.
      Do you know of any algorithms that may achieve this goal that I would be able to look at?
  • Popular Now