• 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
32

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

There are a lot of tutorials about t$$anonymous$$s 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, w$$anonymous$$ch 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;
     }
 }

T$$anonymous$$s is a basic GameData class w$$anonymous$$ch 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 t$$anonymous$$s 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 t$$anonymous$$s 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 w$$anonymous$$ch was read from the file.

The destination will use the Application.persistentDataPath string - w$$anonymous$$ch is located somewhere in the Users/Username/AppData/LocalLow/CompanyName/ProjectName/. The SaveFile() method will create a GameData instance w$$anonymous$$ch 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
avatar image TttGames Bill_G241 · May 31, 2021 at 07:50 PM 0
Share
avatar image ramitLtd · Jun 22, 2021 at 07:56 PM 0
Share
avatar image Eddycted · Feb 05, 2022 at 12:58 PM 0
Share

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.

Welcome to Unity Answers

If you’re new to Unity Answers, please check our User Guide to help you navigate through our website and refer to our FAQ for more information.

Before posting, make sure to check out our Knowledge Base for commonly asked Unity questions.

Check our Moderator Guidelines if you’re a new moderator and want to work together in an effort to improve Unity Answers and support our users.

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

How do I make a level code system? 3 Answers

How to save player score? (C#) 0 Answers

saving IAP data on a database 0 Answers

Why unity tries to save clean assets? 1 Answer

PlayerPrefs Not Saving When I Click the Button. 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