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 /
  • Help Room /
avatar image
5
Question by TheHusk · Jan 16, 2017 at 08:11 PM · saving

How do you save, write, and load from a file?

I just need to know how to create a file, write variables into the file, and then load them out of the file and save into variables in the script. In c#

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
30

Answer by KoenigX3 · Jan 16, 2017 at 11:01 PM

There are a lot of tutorials about this on the internet. I will show you how to create a custom variable holder class and serialize / deserialize it.

First, you need to create a custom class and create variables in it, which you want to store.

 [System.Serializable]
 public class GameData
 {
     public int score;
     public string name;
     public float timePlayed;
 
     public GameData(int scoreInt, string nameStr, float timePlayedF)
     {
         score = scoreInt;
         name = nameStr;
         timePlayed = timePlayedF;
     }
 }

This is a basic GameData class which can hold a score integer, a name string, and the playtime in float. The constructor method below can be used to create an instance of this class and serialize it in a file - we will use that later.

 using System.IO;
 using System.Runtime.Serialization.Formatters.Binary;
 
 public class save : MonoBehaviour {
 
     int currentScore = 0;
     string currentName = "Asd";
     float currentTimePlayed = 5.0f;
 
     void Start()
     {
         SaveFile();
         LoadFile();
     }
 
     public void SaveFile()
     {
         string destination = Application.persistentDataPath + "/save.dat";
         FileStream file;
 
         if(File.Exists(destination)) file = File.OpenWrite(destination);
         else file = File.Create(destination);
 
         GameData data = new GameData(currentScore, currentName, currentTimePlayed);
         BinaryFormatter bf = new BinaryFormatter();
         bf.Serialize(file, data);
         file.Close();
     }
 
     public void LoadFile()
     {
         string destination = Application.persistentDataPath + "/save.dat";
         FileStream file;
 
         if(File.Exists(destination)) file = File.OpenRead(destination);
         else
         {
             Debug.LogError("File not found");
             return;
         }
 
         BinaryFormatter bf = new BinaryFormatter();
         GameData data = (GameData) bf.Deserialize(file);
         file.Close();
 
         currentScore = data.score;
         currentName = data.name;
         currentTimePlayed = data.timePlayed;
 
         Debug.Log(data.name);
         Debug.Log(data.score);
         Debug.Log(data.timePlayed);
     }
 
 }

In this script, we are using other namespaces as well. There are 3 variables in the game - we will save them into a file, and then read them. The Debug.Log() function will return the data which was read from the file.

The destination will use the Application.persistentDataPath string - which is located somewhere in the Users/Username/AppData/LocalLow/CompanyName/ProjectName/. The SaveFile() method will create a GameData instance which will be filled with the current game data. After serialization the file will be closed.

The LoadFile() method will return if the file is not found. On successful deserialization you will get a GameData instance with the saved variables. You can rewrite the current game data variables with these loaded variables.

Comment
Add comment · Show 4 · 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
avatar image Bill_G241 · Mar 20, 2021 at 01:40 PM 0
Share

Very good and save a lot of time. But every time I try to run the program, it overwrite the existing data. I need to add to the current data not to overwrite it.

avatar image TttGames Bill_G241 · May 31, 2021 at 07:50 PM 0
Share

switch Save() and Load() in Start()

avatar image ramitLtd · Jun 22, 2021 at 07:56 PM 0
Share

Hi sorry but as a newbie, it isn't clear to me how the private variables (currentScore, currentName, currentTimePlayed) can be changed within the rest of the game?

If you call Save/SaveFile from another script, the values will not be changed from 0, Asd, 5.0f, respectively, will they?

avatar image Eddycted · Feb 05 at 12:58 PM 0
Share

This is a good example of what a simple save/load system would start as, do note that it is not recommended to use BinaryFormatter if you're not 100% sure what you might load. See: https://docs.microsoft.com/en-us/dotnet/standard/serialization/binaryformatter-security-guide

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

98 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

Related Questions

Why saving scene applies to all scenes in a project 1 Answer

How can I save level progression 1 Answer

How can i save random-generated maps during gameplay ? 1 Answer

Setting components variables with another component 0 Answers

How do I assign a prefab's Instance ID, that was converted to string, as a GameObject variable in a c# script? 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