Unity Export XML configuration file, load scene dynamically

Source: Internet
Author: User
Tags sca xml attribute

Reference: http://www.xuanyusong.com/archives/1919

http://www.omuying.com/article/48.aspxMain functions:1. Export the scene's configuration file2. Export the assetbundle of resources in the current scene3. The client obtains the configuration file from the server4. Parse the configuration file and download Assetbundle according to the configuration file5. Instantiating and restoring a scene1. Scene settings: Set the scene resource you want to export to preset 2. Export the scene configuration as an XML file [Code]csharpcode:
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 (" Objectasseturl ", 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 ()) ;p Ositionxmlelement.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 ();}}}

Export Results Reference:

[Code]xmlcode:
<?xml version= "1.0" encoding= "Utf-8"?><root> <scene scenename= "Dongtaijiazaitest" > <gameObject Objectname= "box" objectasseturl= "box" > <transform> <position x= " -1.293883" y= " -0.07" z= "1.41"/&gt        ; <rotation x= "y=" 0 "z=" 0 "/> <scale x=" 1 "y=" 1 "z=" 1 "/> </transform> </gameobject > <gameobject objectname= "MEINV" objectasseturl= "MEINV" > <transform> <position x= "-1.75" Y= "1.36" z= "11.28"/> <rotation x= "0" y= "97.43578" z= "0"/> <scale x= "1.09" y= "1.09" z= "1.09"/&      Gt </transform> </gameObject> <gameobject objectname= "envirment" objectasseturl= "envirment" > &lt ;transform> <position x= "0" y= "0" z= "0"/> <rotation x= "0" y= "0" z= "0"/> <scale x=  "1" y= "1" z= "1"/> </transform> </gameObject> <gameobject objectname= "Rigidbodyfpscontroller" ObjectaSseturl= "Rigidbodyfpscontroller" > <transform> <position x= "4.89" y= "1.46" z= "0.87"/> &L T;rotation x= "0" y= "253.2478" z= "0"/> <scale x= "1" y= "1" z= "1"/> </transform> </gameobj ect> <gameobject objectname= "Sphere" objectasseturl= "Sphere" > <transform> <position x= "-2      . "Y=" 3.28 "z=" -3.95 "/> <rotation x=" "" y= "0" z= "0"/> <scale x= "1" y= "1" z= "1"/> </transform> </gameObject> </scene></root>

3. Package The Presets as Assetbundle and upload them to the serverPackage Assetbundle Editor Script:[Code]csharpcode:
Using unityengine;using system.collections;using unityeditor;public class test:editor{[MenuItem ("Custom editor/creat        E assetbunldes Main for Android ")] static void Createassetbunldesmainforandroid () {//Get all Game objects selected in Project view        object[] Selectedasset = selection.getfiltered (typeof (Object), selectionmode.deepassets); Traverse all Game objects foreach (Object obj in Selectedasset) {//local test: It is recommended to put Assetbundle in the Streamingassets folder finally.            If you do not create one, because the mobile platform can only read this path//streamingassets is a read-only path, can not write//server download: There is no need to put it here, the client on the server with the WWW class to download.            String TargetPath = Application.datapath + "/streamingassets/" + obj.name + "Android" + ". Assetbundle"; if (buildpipeline.buildassetbundle (obj, null, TargetPath, Buildassetbundleoptions.collectdependencies,            buildtarget.android) {Debug.Log (Obj.name + "Resource Package success");            } else {Debug.Log (obj.name + "resource packaging failed");       } }//Refresh Editor Assetdatabase.refresh ();         } [MenuItem ("Custom editor/create assetbunldes Main for IPhone")] static void Createassetbunldesmainforiphone () { Get all Game objects selected in Project View object[] Selectedasset = selection.getfiltered (typeof (Object), Selectionmode.deepa        Ssets); Traverse all Game objects foreach (Object obj in Selectedasset) {string TargetPath = Application.datapath + "/            streamingassets/"+ obj.name +" IPhone "+". Assetbundle "; if (buildpipeline.buildassetbundle (obj, null, TargetPath, Buildassetbundleoptions.collectdependencies,            Buildtarget.iphone) {Debug.Log (Obj.name + "Resource Package success");            } else {Debug.Log (obj.name + "resource packaging failed");    }}//Refresh Editor Assetdatabase.refresh ();         } [MenuItem ("Custom editor/create assetbunldes All for Android")] static void Createassetbunldesallforandroid () { Caching.cleancache ();       String Path = Application.datapath + "/streamingassets/allandroid.assetbundle";        object[] Selectedasset = selection.getfiltered (typeof (Object), selectionmode.deepassets);        foreach (Object obj in Selectedasset) {Debug.Log ("Create assetbunldes name:" + obj); }//Note here The second parameter is the line if (Buildpipeline.buildassetbundle (null, Selectedasset, Path, Buildassetbundleoptions.collec        Tdependencies, buildtarget.android)) {Assetdatabase.refresh (); } else {}} [MenuItem ("Custom editor/create assetbunldes All for IPhone")] static void Crea        Teassetbunldesallforiphone () {Caching.cleancache ();        String Path = Application.datapath + "/streamingassets/alliphone.assetbundle";        object[] Selectedasset = selection.getfiltered (typeof (Object), selectionmode.deepassets);       foreach (Object obj in Selectedasset) {Debug.Log ("Create assetbunldes name:" + obj); }//Note here The second parameter is the line if (Buildpipeline.buildassetbundle (null, Selectedasset, Path, Buildassetbundleoptions.colle        Ctdependencies, Buildtarget.iphone)) {Assetdatabase.refresh (); } else {}} [MenuItem ("Custom editor/create Scene for Android")] static void Createsceneall        Forandroid () {Caching.cleancache ();        object[] Selectedasset = selection.getfiltered (typeof (Object), selectionmode.deepassets); foreach (Object obj in selectedasset) {string Path = Application.datapath + "/streamingassets/" + OBJ.N            Ame + "Android" + ". Unity3d";            String[] levels = {@ "assets/scenes/exportedscene/" + obj.name + ". Unity"};            Buildpipeline.buildplayer (Levels, Path, buildtarget.android, buildoptions.buildadditionalstreamedscenes);        Debug.Log ("Craete Scene" + Path + "complete!!");    } Assetdatabase.refresh (); } [MenuItem ("Custom editor/create Scene for IPhone")] static void Createsceneallforiphone () {Caching.cleancache ();        object[] Selectedasset = selection.getfiltered (typeof (Object), selectionmode.deepassets); foreach (Object obj in selectedasset) {string Path = Application.datapath + "/streamingassets/" + OBJ.N            Ame + "IPhone" + ". Unity3d";            String[] levels = {@ "assets/scenes/exportedscene/" + obj.name + ". Unity"};            Buildpipeline.buildplayer (Levels, Path, Buildtarget.iphone, buildoptions.buildadditionalstreamedscenes);        Debug.Log ("Craete Scene" + Path + "complete!!");    } Assetdatabase.refresh (); }}
 4. Modify the path of the server into an XML configuration file and upload the XML to the server  5. Download and parse the XML on the Unity client, download and instantiate the corresponding resource [Code]csharpcode:
Using unityengine;using system.collections;using system.io;using system.collections.generic;using System.Xml;public Class Getxmldoc:monobehaviour{string Filepath;public string xmldocurl = "Http://************.xml"; void Awake () { FilePath = Application.persistentdatapath + "/xmldoc1028.xml", if (file.exists (FilePath)) {file.delete (FilePath);} www www = new www (xmldocurl); Startcoroutine (Downloadxmldoc (WWW));} IEnumerator Downloadxmldoc (www www.) {yield return www;if (www.isDone) {Debug.Log ("www is done"); byte[] BTS = www.bytes;in T length = BTS. Length; Createxmldoc (FilePath, BTS, length);}} void Createxmldoc (string path, byte[] info, int lenth) {Debug.Log ("Start to create XML"); Stream SW; FileInfo t = new FileInfo (path), if (!t.exists) {SW = T.create ();} else {return;} Sw. Write (info, 0, lenth); SW. Close (); SW. Dispose ();D ebug. Log ("XML create sucess"); Loadscene ()///After downloading, you can read and instantiate the}void Loadscene () {Debug.Log ("Start loading"), if (File.exists (FilePath)) {XmlDocument XML Doc = new XmldoCument (); Xmldoc.load (FilePath); XmlNodeList nodeList = Xmldoc.selectsinglenode ("root").                Childnodes;foreach (XmlElement scene in nodeList) {//Because my XML is to export all of the game objects, so here's to judge only the game objects in the scene that need to be parsed//json and it works like// if (!scene. GetAttribute ("name"). Equals ("assets/startrooper.unity"))//{//continue;//} foreach (Xmleleme NT gameobjects in scene. ChildNodes) {//Get resource address string Assetrul = Gameobjects.getattribute ("Objectasseturl"); string assetname = Gameobjects.getattribute ("ObjectName"); Vector3 pos = Vector3.zero; Vector3 rot = Vector3.zero; Vector3 SCA = Vector3.zero;foreach (XmlElement transform in Gameobjects.childnodes) {foreach (XmlElement prs in transform). ChildNodes) {if (PRS). Name = = "position") {pos.x = float. Parse (PRS. GetAttribute ("x"));p Os.y = float. Parse (PRS. GetAttribute ("y"));p os.z = float. Parse (PRS. GetAttribute ("z"));//foreach (XmlElement position in PRS. ChildNodes) {//switch (position. Name) {//case "x"://pos.x= float. Parse (position. InnerText);//break;//case "Y"://pos.y = float. Parse (position. InnerText);//break;//case "Z"://pos.z = float. Parse (position. InnerText);//break;//}//}} else if (PRS. Name = = "Rotation") {rot.x = float. Parse (PRS. GetAttribute ("x")); rot.y = float. Parse (PRS. GetAttribute ("Y")); rot.z = float. Parse (PRS. GetAttribute ("z"));//foreach (XmlElement rotation in PRS. ChildNodes) {//switch (rotation. Name) {//case "x"://rot.x = float. Parse (rotation. InnerText);//break;//case "Y"://rot.y = float. Parse (rotation. InnerText);//break;//case "Z"://rot.z = float. Parse (rotation. InnerText);//break;//}//}} else if (PRS. Name = = "scale") {sca.x = float. Parse (PRS. GetAttribute ("x")); sca.y = float. Parse (PRS. GetAttribute ("Y")); sca.z = float. Parse (PRS. GetAttribute ("z"));//foreach (XmlElement scale in PRS. ChildNodes) {//switch (scale. Name) {//case "x"://sca.x = float. Parse (scale. InnerText);//break;//case "Y"://sca.y = float. Parse (scale. InnerText);//break;//case "Z"://sca.z = float. Parse (scale.InnerText);//break;//}//}}}debug.log ("Ready to Download:" + Assetrul);//start downloading and instantiating objects Debug.Log (assetname + ":p os = "+ pos";D ebug. Log (Assetname + ": rot=" + pos);D ebug. Log (Assetname + ": sca=" + pos); Startcoroutine (Downloadasset (New WWW (Assetrul), POS, Rot, SCA));//Get rotated Zoom translation after clone new game object//Gameob ject OB = (gameobject) instantiate (Resources.load (Asset), POS, Quaternion.euler (ROT));//Ob.transfor                     M.localscale = SCA;            }}}}}ienumerator Downloadasset (www www, Vector3 pos, Vector3 rot, Vector3 SCA) {yield return www;if (www.isDone) {// Yield return instantiate (Www.assetBundle.mainAsset,pos,pos,Quaternion.Euler (Rot)); Gameobject ob = (gameobject) instantiate (Www.assetBundle.mainAsset, POS, Quaternion.euler (Rot)); O B.transform.localscale = Sca;www.assetbundle.unload (false);}}}

(GO) Unity Export XML configuration file, load scene dynamically

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.