Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 12 Next capture
2021 2022 2023
1 capture
12 Jun 22 - 12 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
0
Question by corbinyo · Mar 29, 2018 at 08:15 PM · jsonslider

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");
             }
         }
     }
 }
Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
0

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);

Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

77 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

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


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges