Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 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 DrowningGeodude · Jan 01 at 09:54 PM · scripting problemjsonsave data

Need help on Json Script

Hi, I have a project originally using binary formatter to save data and decided to switch to Json, but have been struggling to get it to work ever since. I use a code to set my serializable health to my player's current health every time it takes damage or gains hp but If I try to load, the health just starts at 0.

Edit:Sorry for the messy looking code again, can someone tell me how to post scripts, can't find the guideline that is suppose to show me and am getting frustrated with the automated correction.

Here are the scripts I used for saving my player's health:

{

 public static string directory = "/SaveData/";
 public static string fileName  = "MyData.txt";

 public static void Save(Maxplayerhealth.SaveHealth health)
 {
     string dir = Application.persistentDataPath + directory;
     if (Directory.Exists(dir))
         Directory.CreateDirectory(dir);

     string json = JsonUtility.ToJson(health);
     File.WriteAllText(dir + fileName, json);
 }

 public static Maxplayerhealth.SaveHealth Load()
 {
     string fullPath = Application.persistentDataPath + directory + fileName;
     Maxplayerhealth.SaveHealth health = new Maxplayerhealth.SaveHealth();

     if(File.Exists(fullPath))
     {
         string json = File.ReadAllText(fullPath);
         health = JsonUtility.FromJson<Maxplayerhealth.SaveHealth>(json);
     }
     else
     {
         Debug.Log("Save file does not exist");
     }
     
     return health;

 }

}


public SaveHealth saveH;

public static int maxhealth; {

public int playerHealth = 100;

public static bool intitle;

void Start() {

     Debug.Log(saveH.savehealth);
     maxhealth = playerHealth;

 if (intitle)
     {
         StartCoroutine(sethealth());

     }
 
     
                 healthBar.SetMaxHealth(maxhealth);
   
  
 }

[System.Serializable] public class SaveHealth {

     public int savehealth;
     public int savecurrency;
 }

IEnumerator sethealth() {

    yield return new WaitForSeconds(.1f);
     maxhealth = saveH.savehealth;
   healthBar.SetMaxHealth(maxhealth);
    healthBar.SetHealth(playerHealth);
   }

private void Update

{

if (healthcollected == true) {

         maxhealth += 10;
         upgradedHealth += 10;
         playerHealth = maxhealth;
        
         healthBar.SetMaxHealth(maxhealth);
         healthcollected = false;
         saveH.savehealth = playerHealth;
         Debug.Log(saveH.savehealth + " saveHP");
     }

}

private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.CompareTag("Enemy") || collision.gameObject.CompareTag("Spike") && canbedamage == true)

 {  
        Physics2D.IgnoreLayerCollision(7, 9, true);
         Physics2D.IgnoreLayerCollision(7, 14, true);
         canbedamage = false;
         StartCoroutine(Invulnerable());
         playerHealth -= damage;
         saveH.savehealth = playerHealth;
         healthBar.SetHealth(playerHealth);
       
         
          Damageanimate();
     }

}


if (Input.GetKeyDown(KeyCode.W)) { StartCoroutine(SavePlayer()); }

     if (intitle == true)
 {
    
     intitle = false;
        LoadPlayer();
     }

IEnumerator SavePlayer() { yield return new WaitForSeconds(3.5f);

        Debug.Log("SaveThis");
     JsonSaveManager.Save(health);
 

}

public void LoadPlayer() {

     health = JsonSaveManager.Load();
  


 }


Comment
Add comment · Show 3
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
avatar image xxmariofer · Jan 02 at 10:36 PM 1
Share

Is the txt file being updated? Have you checked manually? For putting code, there is a button with the numbers

 101
 010

Click them and paste the code in the box

avatar image DrowningGeodude xxmariofer · Jan 02 at 11:33 PM 0
Share

I'm not sure, I have to check that out.

avatar image DrowningGeodude · Jan 07 at 12:11 PM 0
Share

@xmariofer thanks for helping me again, I checked where it is suppose to save and I learn that the file is not being saved at all for some reason. I tried doing the script again but in the exact way from the tutorial I'm following and for some reason it is still not working.

 public static class SaveManager
 {
 
     public static string directory = "/SaveData/";
     public static string fileName = "MuData.txt";
 
 
     public static void Save(SaveObject so)
     {
         string dir = Application.persistentDataPath + directory;
 
         if(Directory.Exists(dir))
         
             Directory.CreateDirectory(dir);
 
             string json = JsonUtility.ToJson(so);
             File.WriteAllText(dir + fileName, json);
         
     }
 
     public static SaveObject Load()
     {
         string fullPath = Application.persistentDataPath + directory + fileName;
         SaveObject so = new SaveObject();
 
         if(File.Exists(fullPath))
         {
             string json = File.ReadAllText(fullPath);
             so = JsonUtility.FromJson<SaveObject>(json);
         }
         else
         {
             Debug.Log("Save file does not exist");
         }
         return so;
 
     }
 }

 public class SaveTest : MonoBehaviour
 {
     public SaveObject so;
   
     void Update()
     {
         if(Input.GetKeyDown(KeyCode.Space))
         {
             SaveManager.Save(so);
         }
 
         if(Input.GetKeyDown(KeyCode.Return))
         {
             so = SaveManager.Load();
         }
 
         
     }
 }

 [System.Serializable]
 public class SaveObject 
 {
     public string playerName;
     public int playerLevel;
     public int playerGold;
     public int playerLives;
 }

Here is the tutorial I am following if you are interested: https://www.youtube.com/watch?v=aV2OA4f5ru8

and again, thank you for your time.

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Bunny83 · Jan 07 at 12:53 PM

Here is the tutorial I am following

Well, you did not follow the tutorial very well. This line:

 if(Directory.Exists(dir))

should be

 if(!Directory.Exists(dir))

When you follow a tutorial, the main goal is to understand how to express a certain goal in the target language C#. Are you sure you tried to understand what is happening logically? Your code checks if the directory exists and if it exists you create it. So if it does not exist, you do not create it. This makes no sense :)


Of course you should create the directory in case it does not exist. That's what the code in the tutorial does.


Also, what IDE are you using to write your code? Your indention is off. Only the Directory.CreateDirectory(dir); line is affected by the if statement since there are no curly braces. So only that line should be indented. The following lines are outside the if statement.

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

236 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 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 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 avatar image avatar image avatar image avatar image avatar image

Related Questions

Deserialize Json into list.,how to deserialize a list via .FromJson 1 Answer

Unity google save cloud service: How to build a good save system? 0 Answers

How to calculate specific data before build and save it? 1 Answer

How to store a nullable int into a .json file? 1 Answer

JSON not saving game object list 0 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