Unity3d scenes into XML and parse the restore scene

Source: Internet
Author: User
Tags xml attribute xpath

In order to speed up the scene from the network as much as possible, we can usually lead the scene into XML, prioritize high-priority resources to load and display (terrain, etc.), put the objects that can be loaded into the scene after the final (such as the scene of monsters, etc.), this part of the code is referenced from:/http www.xuanyusong.com/archives/1919, the export scene section is optimized for the original author's code base, and is organized into a more convenient and easy-to-use class library.

First set up the test scenario (test scenario Source network), and organize the objects in the scene,

Then the objects in the scene are set to a preset, easy to package into a Assetbundle file (how to package presets, see),

Then we write the code to package the scene into XML, named ExportSceneToXml.cs, you can first read this article (http://www.xuanyusong.com/archives/1919), I have been optimized on this basis, The full code is as follows:

Using unityengine;using unityeditor;using system.collections;using system.collections.generic;using System.Xml; Using system.io;using System.text;public class Exportscenetoxml:editor {[MenuItem ("Assets/export Scene to XML from Selec tion ")]static void ExportXML () {String path = Editorutility.savefilepanel (" Save Resource "," "," New Resource "," xml "); Path. Length! = 0) {object[] selectedassetlist = selection.getfiltered (typeof (Object), selectionmode.deepassets);// Traverse all Game objects foreach (Object SelectObject in Selectedassetlist) {//scene name string scenename = selectobject.name;//Scene Path string SC Enepath = Assetdatabase.getassetpath (SelectObject);//Scene file//string xmlpath = path; Application.datapath + "/assetbundles/prefab/scenes/" + Scenename + ". xml";//If there is a scene file, delete if (file.exists (path)) File.delete (path);//Open this level editorapplication.openscene (Scenepath); XmlDocument XmlDocument = new XmlDocument ();//create XML attribute XmlDeclaration XmlDeclaration = xmldocument.createxmldeclaration ("1.0", "Utf-8", null); xmldocUment. AppendChild (XmlDeclaration);//create XML root flag XmlElement rootxmlelement = xmldocument.createelement ("root");// Create scene flag XmlElement scenexmlelement = xmldocument.createelement ("Scene"), Scenexmlelement.setattribute ("Scenename", Scenename), foreach (Gameobject sceneobject in Object.findobjectsoftype (typeof (Gameobject))) {//If the object is an active state if ( SceneObject.transform.parent = = NULL && sceneobject.activeself) {//Determine if it is a preset if (Prefabutility.getprefabtype ( Sceneobject) = = prefabtype.prefabinstance) {//Get reference preset Object prefabobject = Editorutility.getprefabparent ( Sceneobject); if (prefabobject! = null) {XmlElement gameobjectxmlelement = xmldocument.createelement ("Gameobject"); Gameobjectxmlelement.setattribute ("ObjectName", Sceneobject.name); Gameobjectxmlelement.setattribute (" Objectasset ", prefabobject.name); XmlElement transformxmlelement = xmldocument.createelement ("transform");//Position information XmlElement positionxmlelement = Xmldocument.createelement ("position");p Ositionxmlelement.setattribute ("x", Sceneobject.transfOrm.position.x.tostring ());p Ositionxmlelement.setattribute ("Y", sceneobject.transform.position.y.tostring ()); Positionxmlelement.setattribute ("Z", Sceneobject.transform.position.z.tostring ());//Rotation Information XmlElement Rotationxmlelement = Xmldocument.createelement ("rotation"); Rotationxmlelement.setattribute ("X", Sceneobject.transform.rotation.eulerangles.x.tostring ()); Rotationxmlelement.setattribute ("Y", Sceneobject.transform.rotation.eulerangles.y.tostring ()); Rotationxmlelement.setattribute ("Z", Sceneobject.transform.rotation.eulerangles.z.tostring ());//Zoom information XmlElement scalexmlelement = Xmldocument.createelement ("scale"); Scalexmlelement.setattribute ("X"), Sceneobject.transform.localscale.x.tostring ()); Scalexmlelement.setattribute ("Y", Sceneobject.transform.localscale.y.tostring ()); Scalexmlelement.setattribute ("Z", Sceneobject.transform.localscale.z.tostring ()); Transformxmlelement.appendchild (positionxmlelement); Transformxmlelement.appendchild (rotationxmlelement); Transformxmlelement.appendchild (Scalexmlelement); Gameobjectxmlelement.appendchild (transformxmlelement); Scenexmlelement.appendchild (gameObjectXmlElement);}}} Rootxmlelement.appendchild (scenexmlelement); Xmldocument.appendchild (rootxmlelement);//Save Scene Data Xmldocument.save ( path);//Refresh Project view Assetdatabase.refresh ();}}}

Then we select the scenario that needs to be packaged, choose the option to package the scene into XML,

When the build is complete, we can view the generated XML content,

Why is it that the code of the original author is optimized, we can change the name of an object in the scene to be different from the preset name,

Then export the XML file again to view the XML generated content we can find that we can correctly find the preset name,

In addition, we can choose which files in the scene do not export, the method is very simple, we can first disable the object in the scene, and then export,

Looking again at the newly exported XML file, we find that the configuration information for the disabled object is not included in the XML.

The above two points is the original author code optimization, and I also changed to use right-click Export, personal feeling so more convenient and practical.

Now back in the scene, we can delete all the objects in the scene, because these objects are not needed in the scene, and we need to create them through code.

Here we see how to restore the scene, with XML, we can parse the XML, the load of resources can see this article (see details), loading the scene and the default resources (Assetbundle) code is as follows:

Using unityengine;using System.collections.generic;public class Loaderscene:monobehaviour {public UISlider Progressbar;public UILabel lblstatus;private string scenepath;void Awake () {string prefabpath = "file:///" + Application.datapath + "/assets/{0}.assetbundle"; this.scenepath = "file:///" + Application.datapath + "/Assets/ Mainscene.unity3d ";ilist<wwwloaderpath> pathList = new list<wwwloaderpath> ();p Athlist.add (new Wwwloaderpath (This.scenepath, Random.range (0, +), wwwloadertypeenum.unity_3d));p Athlist.add (New WwwLoaderPath ( String. Format (Prefabpath, "Lights"), Random.range (0, +), Wwwloadertypeenum.asset_bundle));p Athlist.add (New Wwwloaderpath (String. Format (Prefabpath, "particles"), Random.range (0, +), Wwwloadertypeenum.asset_bundle));p Athlist.add (new Wwwloaderpath (String. Format (Prefabpath, "Physicscube"), Random.range (0, +), Wwwloadertypeenum.asset_bundle));p Athlist.add (new Wwwloaderpath (String. Format (Prefabpath, "Player"), Random.range (0, +), WwWloadertypeenum.asset_bundle));p the Athlist.add (new Wwwloaderpath (string. Format (Prefabpath, "stamps"), Random.range (0, +), Wwwloadertypeenum.asset_bundle));p Athlist.add (New Wwwloaderpath (String. Format (Prefabpath, "Statics"), Random.range (0, +), Wwwloadertypeenum.asset_bundle));p Athlist.add (new Wwwloaderpath (String. Format (Prefabpath, "Terrain"), Random.range (0, Wwwloadertypeenum.asset_bundle));p Athlist.add (new Wwwloaderpath (String. Format (Prefabpath, "Trees"), Random.range (0, +), wwwloadertypeenum.asset_bundle)); this.lblStatus.text = "Scene loading, please wait ... "; WwwLoaderManager.instance.Loader (PathList, onloaderprogress, Onloadercomplete, "Mainscene");} private void Onloaderprogress (string path, float currentvalue, float totalvalue) {this.progressBar.value = CurrentValue;} private void Onloadercomplete () {this.lblStatus.text = "The scene is initializing, please wait ... "; Application.loadlevelasync ("Mainscene");}}

The

then creates a new C # file, named: InitObject.cs, with the following code:

Using unityengine;using system.collections;using System.xml;public class Initobject:monobehaviour {void Awake () { String Xmlpath = Application.datapath + "/assets/mainscene.xml"; string prefabpath = "file:///" + Application.datapath + "/ Assets/{0}.assetbundle "; XmlDocument XmlDocument = new XmlDocument () xmldocument.load (Xmlpath);//use XPATH to get all gameobject nodes XmlNodeList Xmlnodel ist = xmldocument.selectnodes ("//gameobject"); foreach (XmlNode XmlNode in XmlNodeList) {string gameobjectname = xmlnode.attributes["ObjectName"]. value;string prefabname = xmlnode.attributes["Objectasset"]. Value; Assetbundle Assetbundle = WwwDataManager.instance.GetDataAssetBundle (string. Format (Prefabpath, prefabname)); if (assetbundle! = null) {Gameobject Assetobject = (gameobject) assetbundle.load ( Prefabname, typeof (Gameobject)), if (assetobject! = null) {Gameobject Gameobject = (gameobject) instantiate (Assetobject) ;//Use XPATH to get position, rotate, scale data xmlNode Positionxmlnode = Xmlnode.selectsinglenode ("descendant::p osition"); XmlNode Rotationxmlnode = Xmlnode.selectsinglenode ("descendant::rotation"); XmlNode Scalexmlnode = Xmlnode.selectsinglenode ("Descendant::scale"); if (Positionxmlnode! = null && Rotationxmlnode = null && Scalexmlnode! = null) {gameObject.transform.position = new Vector3 (float. Parse (positionxmlnode.attributes["x"]. Value), float. Parse (positionxmlnode.attributes["Y"]. Value), float. Parse (positionxmlnode.attributes["Z"]. Value); gameObject.transform.rotation = Quaternion.euler (new Vector3 (float). Parse (rotationxmlnode.attributes["x"]. Value), float. Parse (rotationxmlnode.attributes["Y"]. Value), float. Parse (rotationxmlnode.attributes["Z"]. Value)); GameObject.transform.localScale = new Vector3 (float. Parse (scalexmlnode.attributes["x"]. Value), float. Parse (scalexmlnode.attributes["Y"]. Value), float. Parse (scalexmlnode.attributes["Z"]. Value));}} Unload the referenced load resource, freeing the memory Assetbundle.unload (FALSE);}} xmlDocument = null;}}

Then we create a new empty object in the empty scene, and attach the code to the empty object,

Then we package this scene into a. unity3d file that is easy to load from the network (see this article for details) so that all the preparation is done, all the configuration files and resource files are as follows:

We run the project from the load scene, we can first see in order to load the main scene resource, after loading completed into the main scene, according to the XML content, the original scene was restored back,

Original link: http://www.omuying.com/article/48.aspx

Unity3d scenes into XML and parse the restore scene

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.