- Home /
Export level to be loaded in game
Hi everyone!
I am making a game like "build and share". What that means is that players can build stuff in-game and then share with everyone! But what I need is to export the level in a specific format and to be loaded again. When it exports, you can save it where ever you want. Like on your desktop and name is whatever. Then in-game, you can load the level and it will load everything. Including skybox, camera, all items in the scene e.t.c.
So, if you know a way to do this, please tell me!
Thanks!
P.S. If it is possible to make a custom file format, please tell me. :)
Firstly, create a class to hold your whole data. Then, serialize that with xmlSerializer. Write it to a file with whatever extension you want. I suggest reading: XmlSerializer
I don't know how to make a class that holds the whole data.
Answer by Ashish Dwivedi · Feb 07, 2014 at 11:18 AM
Here is one script in which reading , writing and deleting is there. You can understand and modify according to your requairement.
using UnityEngine;
using System.Collections;
using System.Xml;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System;
public class LevelManager : MonoBehaviour
{
#region Declaration
GameManager mGameManager;
public GameObject [] _arrObjects ;
ArrayList alObjects;
int miLevelNumber ;
#endregion
#region BuiltInMethods
// Use this for initialization
void Start ()
{
alObjects = new ArrayList();
mGameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
miLevelNumber = 0;
}
// void CallBack(object j)
// {
// Debug.Log("Call back By me");
// }
#endregion
#region XMLHandler
/// <summary>
/// Saves the objects data.
/// </summary>
/// <param name="iLevel">Level Number</param>
/// <param name="arrObjects">Array of objects</param>
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;
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;
_FileLocation = path + "/Assets/GameXmlDocuments/"+GameName;
if(Directory.Exists(_FileLocation))
{
}
else
{
Directory.CreateDirectory(_FileLocation);
}
//_FileLocation =path + "/Documents/GameXmlDocuments/"+GameName+"/";
_FileLocation =path + "/Assets/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+"/";
_FileLocation = path + "/Assets/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";
_FileLocation = path + "/Assets/GameXmlDocuments/MyGame";
if(Directory.Exists(_FileLocation))
{
//_FileLocation =path + "/Documents/GameXmlDocuments/MyGame/" + "Level" + iLevel + "Data.xml";
_FileLocation =path + "/Assets/GameXmlDocuments/MyGame/" + "Level" + iLevel + "Data.xml";
File.Delete(_FileLocation);
}
}
#endregion
#region Instantiation
/// <summary>
/// Instantiates the object.
/// </summary>
/// <param name="pos">Position</param>
/// <param name="rot">Rotation</param>
/// <param name="sca">Scaling</param>
/// <param name="sName">Object Name</param>
void InstantiateObject(Vector3 pos , Quaternion rot , Vector3 sca , string sName)
{
GameObject obs = null;
for(int i = 0 ; i < _arrObjects.Length ; i++)
{
if(_arrObjects[i].name == sName)
{
obs = _arrObjects[i];
break;
}
}
GameObject obstacle = (GameObject) Instantiate(obs , new Vector3(pos.x , pos.y , pos.z) ,new Quaternion(rot.x , rot.y , rot.z , rot.w));
obstacle.transform.localScale = new Vector3(sca.x , sca.y , sca.z);
obstacle.name = obs.name;
if(mGameManager.NumberOfBalls >= 0 && obstacle.name == "Ball")
{
mGameManager.SetBallPosition(new Vector2(pos.x , pos.y));
mGameManager.AssignBall(obstacle);
}
else if(obstacle.name == "Player")
{
obstacle.GetComponent<Collider2D>().enabled = false;
mGameManager.AssignPlayer(obstacle);
}
}
// public List<int> GetLevelList()
// {
// List<int> lLevel = new List<int>();
// string filePath;
//
// for(int i = 1; i<= mGameManager.NumberOfLevels ; i++)
// {
// try
// {
// filePath = GetFilePath("Level"+ i +"Data.xml","MyGame");
// XmlDocument xmlDoc = new XmlDocument();
// xmlDoc.Load(filePath);
// lLevel.Add(i);
// }
// catch(FileNotFoundException)
// {
//
// }
// }
// return lLevel;
// }
#endregion
}
In this XMLSerialzation is not used. That is for better performance if you want then you can use by self.
When I apply it for the first time when I was just going to test it, it gave me an error. "The type or namespace name 'Game$$anonymous$$anager' could not be found. Are you missing a using directive or an assembly reference?"
No it's not, that is my project script and having reference for other scripts that's why you are getting error. Simply comment those lines which are giving error and try to understand how to use this code. You need to modify according to your requirement. Still if you are not getting then attach you X$$anonymous$$L file having data and I will send you script according to your requirement.