Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
13 Jun 22 - 14 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 burchland2 · Sep 09, 2021 at 03:13 PM · saveload

Cannot load a saved game

Hello,

I tried to save a game, next close the game, and then load the game. But although I saved it, when I press the LOAD button in during gameplay, it would not load anything, not even load the saved position. Here is the save/load code that I wrote so far.

 using UnityEngine;
 using System;
 using System.IO;
 using System.Runtime.Serialization;
 using System.Runtime.Serialization.Formatters.Binary;
 
 public static class SaveManager 
 {
     public static string directory = "SaveData";
     public static string fileName = "player.game";
 
     public static void SaveGame(Player player)
     {
         if (!(DirectoryExists()))
         {
             Directory.CreateDirectory(Application.persistentDataPath + "/" + directory);
         }
 
         BinaryFormatter bf = new BinaryFormatter();
         FileStream file = File.Create(GetFullPath());
         Save sav = new Save(player);
         bf.Serialize(file, sav);
 
         Debug.Log("Your game has been saved.");
         file.Close();
     }
 
     public static Save LoadGame()
     {
         if (SaveExists())
         {
             try
             {
                 BinaryFormatter bf = new BinaryFormatter();
                 FileStream file = File.Open(GetFullPath(), FileMode.Open);
                 Save sav = (Save)bf.Deserialize(file);
                 Debug.Log("Your game has been loaded.");
                 file.Close();
 
                 return sav;
             }
             catch (SerializationException)
             {
                 Debug.LogError("Failed to save file");
             }
         }
         return null;
     }
 
     private static bool SaveExists()
     {
         return File.Exists(GetFullPath());
     }
 
     private static bool DirectoryExists()
     {
         return Directory.Exists(Application.persistentDataPath + "/" + directory);
     }
 
     private static string GetFullPath()
     {
         return Application.persistentDataPath + "/" + directory + "/" + fileName;
     }
 }

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 [System.Serializable]
 public class Save
 {
     public int score;
     public int lives;
     public int health;
     public float[] position;
     
     public Save(Player player)
     {
         score = player.score;
         lives = player.lives;
         health = player.health;
 
         position = new float[2];
         position[0] = player.transform.position.x;
         position[1] = player.transform.position.y;
     }
 }

 using System.Collections;
 using System.Collections.Generic;
 using UnityEngine;
 
 public class Player : MonoBehaviour
 {
     public int score;
     public int lives;
     public int health;
     
     public void Save()
     {
         SaveManager.SaveGame(this);
     }
 
     public void Load()
     {
         Save sav = SaveManager.LoadGame();
 
         score = sav.score;
         lives = sav.lives;
         health = sav.health;
 
         Vector2 position;
         position.x = sav.position[0];
         position.y = sav.position[1];
         transform.position = position;
     }
 }
 

Can anyone help? Any assistance would be appreciated.

Sincerely, burchland2

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 · Sep 09, 2021 at 04:26 PM

Well, saving and loading / restoring all this information involves many tiny things and a lot things in between could fail. So what have you already done to debug your issue? First of all, do you get any errors or warnings? Have you tried adding more Debug.Log statements across your code? Also try logging the position that is loaded to see if it gets back as you had expected. Finally Your issue could be some sort of race condition. Maybe your loading happens before some other script overwrites your changes? We don't know when or where your Save and Load methods get called. That's something you have to check yourself, we can not do that for you, we don't have your project ^^.


I just like to add that I saw a lot of similar code by other peoples. I guess this is based on some tutorial. That said, first and foremost, the BinaryFormatter should not be used anymore for anything because it's a security risk. Since most get that "security risk" wrong, let me be more clear. This is not about people cheating or altering values in your save. This is about actual security because manipulated save files could cause arbitary code execution of malicious code. So by using the BinaryFormatter you put your user at that risk. Here's the security guide by Microsoft itself. Also, most choose the BinaryFormatter because they think it makes their saved data more secure (in terms of cheating) which is not really the case anyways.


Another critique point about this concept is where the data is handled. The Save constructor takes a player reference and populates itself with the information from the player. However at deserialization the task of reversing the data is carried out by the player class. This is generally a bad design. The serialization and deserialization should be in the same class and the corresponding save and load functions should be "opposites" from each other. In this case the Save function takes a Player instance, the Load function should as well and the deserialization should be handled inside the SaveManager or the Save class.

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

128 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

Related Questions

Terrain: Use as scenario (individual) and prefab (unchanged, reusable) 0 Answers

how to save last position for the player before he die 2 Answers

What is the best way to save data on Android? 0 Answers

Saving and Loading Data with a for loop 2 Answers

SerializationException: Type UnityEngine.Vector3 is not marked as Serializable. 1 Answer


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