- Home /
Why will this script not save slider values to json file? (not getting any response from Debug.Log either)
I have a script here that should work to save all slider values in my scene to a Json file on GetkeyDown.S. Yet nothing is happening and the Debug.Log is not appearing in the console.
If anyone can see a potential issue with this script that would be really helpful!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using LitJson;
using System.Text;
using System;
public class jsonbuttonserialize : MonoBehaviour
{
[SerializeField]
public class Sliders
{
public float value;
public float minValue;
public float maxValue;
public bool wholeNumbers;
public string objName;
}
[SerializeField]
public class SliderInfo
{
public List<Sliders> sliders;
public SliderInfo()
{
sliders = new List<Sliders>();
}
public SliderInfo(Slider[] slider)
{
sliders = new List<Sliders>();
for (int i = 0; i < slider.Length; i++)
AddSlider(slider[i]);
}
public void AddSlider(Slider slider)
{
Sliders tempSlider = new Sliders();
tempSlider.value = slider.value;
tempSlider.minValue = slider.minValue;
tempSlider.maxValue = slider.maxValue;
tempSlider.wholeNumbers = slider.wholeNumbers;
tempSlider.objName = slider.name;
sliders.Add(tempSlider);
}
}
public class DataSaver
{
//Save Data
public static void saveData<T>(T dataToSave, string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Convert To Json then to bytes
string jsonData = JsonUtility.ToJson(dataToSave, true);
byte[] jsonByte = Encoding.ASCII.GetBytes(jsonData);
//Create Directory if it does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
}
//Debug.Log(path);
try
{
File.WriteAllBytes(tempPath, jsonByte);
Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
}
//Load Data
public static T loadData<T>(string dataFileName)
{
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return default(T);
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return default(T);
}
//Load saved Json
byte[] jsonByte = null;
try
{
jsonByte = File.ReadAllBytes(tempPath);
Debug.Log("Loaded Data from: " + tempPath.Replace("/", "\\"));
}
catch (Exception e)
{
Debug.LogWarning("Failed To Load Data from: " + tempPath.Replace("/", "\\"));
Debug.LogWarning("Error: " + e.Message);
}
//Convert to json string
string jsonData = Encoding.ASCII.GetString(jsonByte);
//Convert to Object
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
}
public static bool deleteData(string dataFileName)
{
bool success = false;
//Load Data
string tempPath = Path.Combine(Application.persistentDataPath, "data");
tempPath = Path.Combine(tempPath, dataFileName + ".txt");
//Exit if Directory or File does not exist
if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
{
Debug.LogWarning("Directory does not exist");
return false;
}
if (!File.Exists(tempPath))
{
Debug.Log("File does not exist");
return false;
}
try
{
File.Delete(tempPath);
Debug.Log("Data deleted from: " + tempPath.Replace("/", "\\"));
success = true;
}
catch (Exception e)
{
Debug.LogWarning("Failed To Delete Data: " + e.Message);
}
return success;
}
}
public class buttonsave : MonoBehaviour
{
SliderInfo loadedSliders;
Slider[] slider;
void Start()
{
//Load Slider Settings
loadedSliders = DataSaver.loadData<SliderInfo>("Sliders");
//Get current sliders in the Scene
slider = FindObjectsOfType(typeof(Slider)) as Slider[];
}
void Update()
{
if (Input.GetKeyDown(KeyCode.S))
{
Slider[] slider = FindObjectsOfType(typeof(Slider)) as Slider[];
SliderInfo sliderInfo = new SliderInfo(slider);
//Save Sliders
DataSaver.saveData(sliderInfo, "Sliders");
Debug.Log("hello");
}
}
}
}
Answer by Bunny83 · Mar 30, 2018 at 01:11 AM
The attribute "SerializeField" as the name suggests can only applied to "fields" but not to types like a class. You have to use the "System.Serializable" attribute on classes.
The next potential problem is, why do you actually convert the json string into ascii? JSON by definition can contain any unicode characters and since your data includes a string it could potentially contain other characters than ascii. Simply use WriteAllText which uses utf8 as default encoding.
Finally those two lines seems really strange:
object resultValue = JsonUtility.FromJson<T>(jsonData);
return (T)Convert.ChangeType(resultValue, typeof(T));
FromJson is a generic method which already returns the type "T". You then implicitly up-cast the reference to "object" where the variable looses the type. The ChangeType is completely pointless as ChangeType only makes sense if there actually exists a type conversion. This makes only sense either for built-in primitive types (like int, float, double, ...) or for types that implement the IConvertible. Since your actual object is already of type T there is nothing you can convert the object to.
Just do
return JsonUtility.FromJson<T>(jsonData);
Your answer

Follow this Question
Related Questions
Write multiple GUI slider values to json file in Unity 0 Answers
Binding JSON contents to ui sliders 0 Answers
How can I use one healthbar for different enimes 0 Answers
Vector3 distance to fill slider. 2 Answers
Adjust Brightness Screen 3 Answers