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 RumplyThrower · Jan 30, 2014 at 12:13 PM · savevariablesload

Saving data

I have a lot of objects (planets to be precise) and each of them has a script attached to it with a lot of variables (planet type, resource type, buildings on the planet, level of buildings etc)how can i save and load all of that data?

Comment
Add comment · Show 1
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 GameVortex · Jan 30, 2014 at 12:21 PM 0
Share

http://answers.unity3d.com/questions/8480/how-to-scrip-a-saveload-game-option.html

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by Ashish Dwivedi · Jan 30, 2014 at 12:46 PM

Use XML to save and retrieve the data. Take a look of following code, you will get an idea.

     public void SaveElement(int iLevel , GameObject [] arrObjects)
     {
         alObjects.Clear();
         foreach(GameObject obj in arrObjects)
         {
             alObjects.Add(obj);
         }
         alObjects.TrimToSize();
         
         XmlDocument xmlDoc = new XmlDocument();
         XmlElement rootElement = xmlDoc.CreateElement("Level");
         rootElement.SetAttribute("levelNumber" , iLevel.ToString());
         rootElement.SetAttribute("numberOfBalls" , mGameManager.NumberOfBalls.ToString());
         rootElement.SetAttribute("numberOfGoals" ,  mGameManager.GoalsNeededToCompleteTheLevel.ToString());
         
         XmlElement objectElement = xmlDoc.CreateElement("Objects");
         
         foreach(GameObject obj in alObjects)
         {
             Vector3 obsPos = obj.transform.position;
             Quaternion obsRotation = obj.transform.localRotation;
             Vector3 obsScale = obj.transform.localScale;
             
             XmlElement element = xmlDoc.CreateElement("Object");
             element.SetAttribute("type",obj.name);
             element.SetAttribute("xPosition",obsPos.x.ToString());
             element.SetAttribute("yPosition",obsPos.y.ToString());
             element.SetAttribute("zPosition",obsPos.z.ToString());
             
             element.SetAttribute("xRotation",obsRotation.x.ToString());
             element.SetAttribute("yRotation",obsRotation.y.ToString());
             element.SetAttribute("zRotation",obsRotation.z.ToString());
             element.SetAttribute("wRotation",obsRotation.w.ToString());
             
             element.SetAttribute("xScale",obsScale.x.ToString());
             element.SetAttribute("yScale",obsScale.y.ToString());
             element.SetAttribute("zScale",obsScale.z.ToString());
             
             objectElement.AppendChild(element);
         }
         
         rootElement.AppendChild(objectElement);
         xmlDoc.AppendChild(rootElement);
         
         WriteXMLData(xmlDoc.InnerXml,"Level"+ iLevel +"Data.xml","MyGame");
     }
 
     /// <summary>
     /// Loads the level.
     /// </summary>
     /// <returns><c>true</c>, if level was loaded, <c>false</c> otherwise.</returns>
     /// <param name="iLevel">LevelNumber</param>
     public bool LoadLevel(int iLevel)
     {
         //*************
         mGameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
         //*************
 
         miLevelNumber = iLevel;
         bool bIsLevelExist = true;
         
         string strType;
         int iType = 0;
         Vector3 posObs ;
         Quaternion rotObs ;
         Vector3 scaObs ;
         
         string filePath;
         filePath = GetFilePath("Level"+ iLevel +"Data.xml","MyGame");
         
         try
         {
             XmlDocument xmlDoc = new XmlDocument();
             xmlDoc.Load(filePath);
             
             XmlNode root = xmlDoc.DocumentElement;
             mGameManager.NumberOfBalls = Convert.ToInt32(root.Attributes[1].Value);
             
             mGameManager.GoalsNeededToCompleteTheLevel = Convert.ToInt32(root.Attributes[2].Value);
             
             XmlNodeList nodeListObject = xmlDoc.GetElementsByTagName("Object");
             
             for(int i = 0; i < nodeListObject.Count ; i++)
             {
                 strType = nodeListObject[i].Attributes[0].Value;            
                 
                 float.TryParse( nodeListObject[i].Attributes[1].Value ,out posObs.x );
                 float.TryParse( nodeListObject[i].Attributes[2].Value ,out posObs.y );
                 float.TryParse( nodeListObject[i].Attributes[3].Value ,out posObs.z);
                 
                 float.TryParse( nodeListObject[i].Attributes[4].Value ,out rotObs.x );
                 float.TryParse( nodeListObject[i].Attributes[5].Value ,out rotObs.y );
                 float.TryParse( nodeListObject[i].Attributes[6].Value ,out rotObs.z );
                 float.TryParse( nodeListObject[i].Attributes[7].Value ,out rotObs.w );
                 
                 float.TryParse( nodeListObject[i].Attributes[8].Value ,out scaObs.x );
                 float.TryParse( nodeListObject[i].Attributes[9].Value ,out scaObs.y );
                 float.TryParse( nodeListObject[i].Attributes[10].Value ,out scaObs.z );
                 
                 InstantiateObject(posObs , rotObs , scaObs , strType);
             }
             
         }
         catch(FileNotFoundException)
         {
             bIsLevelExist = false;
             mGameManager.ResetValues();
             mGameManager.LevelNumber = iLevel;
             print ("Level FileNotFound !");
         }
         return bIsLevelExist;
     }
 
     /// <summary>
     /// Writes the XML data to file.
     /// </summary>
     /// <param name="data">Data</param>
     /// <param name="filename">Filename</param>
     /// <param name="GameName">Folder name</param>
     public void WriteXMLData(string data , string filename, string GameName)
     {
         var _FileLocation = Application.dataPath;
         _FileLocation = _FileLocation + "/";
         var path = Application.dataPath.Substring (0, Application.dataPath.Length - 5);
         path = path.Substring(0, path.LastIndexOf('/'));
         _FileLocation = path + "/Documents/GameXmlDocuments/"+GameName;  
         
         
         if(Directory.Exists(_FileLocation))
         {
         }
         else 
         {
             Directory.CreateDirectory(_FileLocation);
         }
         
         _FileLocation =path + "/Documents/GameXmlDocuments/"+GameName+"/"; 
         File.WriteAllBytes(_FileLocation+ filename ,ASCIIEncoding.ASCII.GetBytes(data));
     }
 
     /// <summary>
     /// Gets the file path.
     /// </summary>
     /// <returns>The file path</returns>
     /// <param name="filename">File Name.</param>
     /// <param name="GameName">Folder name.</param>
     public  string GetFilePath(string filename, string GameName)
     {
         var _FileLocation = Application.dataPath;
         _FileLocation = _FileLocation + "/";
         var path = Application.dataPath.Substring (0, Application.dataPath.Length - 5);
         path = path.Substring(0, path.LastIndexOf('/'));
         
         _FileLocation = path + "/Documents/GameXmlDocuments/"+GameName+"/"; 
 
         return _FileLocation+filename;
     }
 
     /// <summary>
     /// Delete the level data file.
     /// </summary>
     /// <param name="iLevel">Level Number</param>
     public void CleanLevel(int iLevel)
     {
         mGameManager.DestroyAllObjects();
         mGameManager.ResetValues();
         mGameManager.LevelNumber = iLevel;
         
         var _FileLocation = Application.dataPath;
         _FileLocation = _FileLocation + "/";
         var path = Application.dataPath.Substring (0, Application.dataPath.Length - 5);
         path = path.Substring(0, path.LastIndexOf('/'));
         _FileLocation = path + "/Documents/GameXmlDocuments/MyGame";  
         
         if(Directory.Exists(_FileLocation))
         {
             _FileLocation =path + "/Documents/GameXmlDocuments/MyGame/" + "Level" + iLevel + "Data.xml"; 
             File.Delete(_FileLocation);
         }
     }
     
     #endregion
Comment
Add comment · Show 6 · 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 RumplyThrower · Jan 30, 2014 at 05:31 PM 0
Share

can i add you on facebook or something so you could explain to me how saving to an X$$anonymous$$L file works

avatar image Ashish Dwivedi · Jan 31, 2014 at 03:42 AM 0
Share

Yes, you can add me on skype. This is my user name...

ashish.kumar@dumadu.com

avatar image flamy · Jan 31, 2014 at 07:17 AM 0
Share

this is a very slow method, you can do xml serialization and deserialization or even use a local db (sqlite) to achieve it with more smoothness

avatar image Ashish Dwivedi · Jan 31, 2014 at 10:08 AM 0
Share

Thanks for your suggestion...

avatar image RumplyThrower · Feb 01, 2014 at 12:17 PM 0
Share

i added you on skype

Show more comments

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

22 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

Related Questions

Problem with Loading States 0 Answers

Load XML File ? 1 Answer

Save variable value. 1 Answer

player prefs, problem but no problem??? 1 Answer

Perform action on save/load in editor 2 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