- Home /
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?
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
can i add you on facebook or something so you could explain to me how saving to an X$$anonymous$$L file works
Yes, you can add me on skype. This is my user name...
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
Your answer
Follow this Question
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