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 RealMTG · Feb 06, 2014 at 05:16 PM · loadexportingame

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. :)

Comment
Add comment · Show 2
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 KurtGokhan · Feb 06, 2014 at 06:04 PM 0
Share

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

avatar image RealMTG · Feb 06, 2014 at 09:12 PM 0
Share

I don't know how to make a class that holds the whole data.

1 Reply

· Add your reply
  • Sort: 
avatar image
1

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.

Comment
Add comment · Show 3 · 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 RealMTG · Feb 07, 2014 at 03:24 PM 0
Share

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?"

avatar image Ashish Dwivedi · Feb 08, 2014 at 07:22 AM 0
Share

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.

avatar image RealMTG · Feb 08, 2014 at 03:55 PM 0
Share

Oh. I see. $$anonymous$$y bad. But thanks!

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

21 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

Related Questions

Unity 4.0 Flash Export load->unload->load crash 0 Answers

saving data in arrays with c#..how ? ... 1 Answer

Save and load ingame 'projects' 1 Answer

Level exporting (with video example) 1 Answer

Failed To Load Mono Fatal Error when launching a built Unity game 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