参考:http://www.xuanyusong.com/archives/1919

http://www.omuying.com/article/48.aspx
主要功能:
1.导出场景的配置文件
2.导出当前场景中资源的AssetBundle
3.客户端从服务器获取配置文件
4.解析配置文件,并根据配置文件下载AssetBundle
5.实例化并还原场景
1.场景设置:将需要导出的场景资源设置为预设
2.将场景配置导出为XML文件

[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 Selection")]static void ExportXML(){string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "xml");if (path.Length != 0) {Object[] selectedAssetList = Selection.GetFiltered (typeof(Object), SelectionMode.DeepAssets);//遍历所有的游戏对象foreach (Object selectObject in selectedAssetList) {// 场景名称string sceneName = selectObject.name;// 场景路径string scenePath = AssetDatabase.GetAssetPath(selectObject);// 场景文件//string xmlPath = path; //Application.dataPath + "/AssetBundles/Prefab/Scenes/" + sceneName + ".xml";// 如果存在场景文件,删除if(File.Exists(path)) File.Delete(path);// 打开这个关卡EditorApplication.OpenScene(scenePath);XmlDocument xmlDocument = new XmlDocument();// 创建XML属性XmlDeclaration xmlDeclaration = xmlDocument.CreateXmlDeclaration("1.0", "utf-8", null);xmlDocument.AppendChild(xmlDeclaration);// 创建XML根标志XmlElement rootXmlElement = xmlDocument.CreateElement("root");// 创建场景标志XmlElement sceneXmlElement = xmlDocument.CreateElement("scene");sceneXmlElement.SetAttribute("sceneName", sceneName);foreach (GameObject sceneObject in Object.FindObjectsOfType(typeof(GameObject))){// 如果对象是激活状态if (sceneObject.transform.parent == null && sceneObject.activeSelf){// 判断是否是预设if(PrefabUtility.GetPrefabType(sceneObject) == PrefabType.PrefabInstance){// 获取引用预设对象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");// 位置信息XmlElement positionXmlElement = xmlDocument.CreateElement("position");positionXmlElement.SetAttribute("x", sceneObject.transform.position.x.ToString());positionXmlElement.SetAttribute("y", sceneObject.transform.position.y.ToString());positionXmlElement.SetAttribute("z", sceneObject.transform.position.z.ToString());// 旋转信息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());// 缩放信息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);// 保存场景数据xmlDocument.Save(path);// 刷新Project视图AssetDatabase.Refresh();}}}
}

导出结果参考:

[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" /><rotation x="270" 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" /></transform></gameObject><gameObject objectName="Envirment" objectAssetURL="Envirment"><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" /><rotation x="0" y="253.2478" z="0" /><scale x="1" y="1" z="1" /></transform></gameObject><gameObject objectName="Sphere" objectAssetURL="Sphere"><transform><position x="-2.63" y="3.28" z="-3.95" /><rotation x="270" y="0" z="0" /><scale x="1" y="1" z="1" /></transform></gameObject></scene>
</root>

3.将预设打包为AssetBundle,并上传到服务器
打包Assetbundle编辑器脚本:

[code]csharpcode:

using UnityEngine;
using System.Collections;
using UnityEditor;public class Test : Editor
{[MenuItem("Custom Editor/Create AssetBunldes Main For Android")]static void CreateAssetBunldesMainForAndroid(){//获取在Project视图中选择的所有游戏对象Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);//遍历所有的游戏对象foreach (Object obj in SelectedAsset){//本地测试:建议最后将Assetbundle放在StreamingAssets文件夹下,如果没有就创建一个,因为移动平台下只能读取这个路径//StreamingAssets是只读路径,不能写入//服务器下载:就不需要放在这里,服务器上客户端用www类进行下载。string targetPath = Application.dataPath + "/StreamingAssets/" + obj.name + "Android" + ".assetbundle";if (BuildPipeline.BuildAssetBundle(obj, null, targetPath, BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android)){Debug.Log(obj.name + "资源打包成功");}else{Debug.Log(obj.name + "资源打包失败");}}//刷新编辑器AssetDatabase.Refresh();}[MenuItem("Custom Editor/Create AssetBunldes Main For iPhone")]static void CreateAssetBunldesMainForiPhone(){//获取在Project视图中选择的所有游戏对象Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);//遍历所有的游戏对象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 + "资源打包成功");}else{Debug.Log(obj.name + "资源打包失败");}}//刷新编辑器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);}//这里注意第二个参数就行if (BuildPipeline.BuildAssetBundle(null, SelectedAsset, Path, BuildAssetBundleOptions.CollectDependencies, BuildTarget.Android)){AssetDatabase.Refresh();}else{}}[MenuItem("Custom Editor/Create AssetBunldes ALL For iPhone")]static void CreateAssetBunldesALLForiPhone(){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);}//这里注意第二个参数就行if (BuildPipeline.BuildAssetBundle(null, SelectedAsset, Path, BuildAssetBundleOptions.CollectDependencies, BuildTarget.iPhone)){AssetDatabase.Refresh();}else{}}[MenuItem("Custom Editor/Create Scene For Android")]static void CreateSceneALLForAndroid(){Caching.CleanCache();Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);foreach (Object obj in SelectedAsset){string Path = Application.dataPath + "/StreamingAssets/" + obj.name + "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.name + "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.将服务器的路径修改到XML配置文件中,并将XML上传到服务器
5.在Unity客户端下载XML并解析,下载并实例化对应的资源

[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;int 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 ();Debug.Log ("XML create sucess");LoadScene ();
//        下载完毕之后可以读取并进行实例化了}void LoadScene (){Debug.Log ("开始加载");if (File.Exists (filePath)) {XmlDocument xmlDoc = new XmlDocument ();xmlDoc.Load (filePath);XmlNodeList nodeList = xmlDoc.SelectSingleNode ("root").ChildNodes;foreach (XmlElement scene  in nodeList) {//因为我的XML是把所有游戏对象全部导出, 所以这里判断一下只解析需要的场景中的游戏对象//JSON和它的原理类似
//                if (!scene.GetAttribute("name").Equals("Assets/StarTrooper.unity"))
//                {
//                    continue;
//                }foreach (XmlElement gameObjects in scene.ChildNodes) {
//                    取得资源地址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"));pos.y = float.Parse(prs.GetAttribute("y"));pos.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 ("准备下载:" + assetRUL);
//                        开始下载并实例化对象Debug.Log (assetName + ":pos=" + pos);Debug.Log (assetName + ":rot=" + pos);Debug.Log (assetName + ":sca=" + pos);StartCoroutine (DownloadAsset (new WWW (assetRUL), pos, rot, sca));//拿到 旋转 缩放 平移 以后克隆新游戏对象
//                        GameObject ob = (GameObject)Instantiate(Resources.Load(asset), pos, Quaternion.Euler(rot));
//                        ob.transform.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));ob.transform.localScale = sca;www.assetBundle.Unload (false);}}}

转载于:https://www.cnblogs.com/backlighting/p/5061527.html

(转)Unity 导出XML配置文件,动态加载场景相关推荐

  1. Unity动态加载场景

    不用在build setting中设置,使用ab包动态加载场景 1.把场景打成ab包 2.加载ab资源,然后加载场景 demo链接 链接:https://pan.baidu.com/s/1dP9ihT ...

  2. C#架构设计-程序运行时从xml配置文件中加载配置项并设置为全局变量

    场景 C#中全局作用域的常量.字段.属性.方法的定义与使用: https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/102550025 在 ...

  3. android: 静态XML和动态加载XML混合使用,以及重写Layout控件

    近期对android里面控件修改做了很多实验,由于公司需求很多,不得不重写很多控件.程序目标无非是:高效.轻巧.清晰.标准化 完成动态加载Layout有两种方法,依据个人喜好进行选择: 方法1:静态主 ...

  4. Unity制作圆环进度条加载场景资源

    第一步:场景内UI圆环的搭建 新建一张Panel作为背景图,在Panel下新建一张Image命名为RoundImage作为外圆环,在外圆环下新建一张image命名为RoundLoading作为内圆环, ...

  5. Unity记录一次重新加载场景时,报错为MissingReferenceException:

    MissingReferenceException: The object of type 'UIRoomPanel' has been destroyed but you are still try ...

  6. unity动态加载.obj文件相关

    .obj文件加载相关 QA: 要点 .obj文件结构 .mtl文件结构 材质匹配问题 动态加载obj文件 unity资源商城插件:Runtime Obj Importer QA: q: 如何动态加载o ...

  7. Unity3D游戏开发之使用AssetBundle和Xml实现场景的动态加载

    各位朋友,大家好,我是秦元培,欢迎大家关注我的博客,我的博客地址是http://qinyuanpei.com/. 引言 今天我想和大家聊聊在Unity3D中关于场景的动态加载的问题.众所周知在Unit ...

  8. Unity动态加载和内存管理(三合一)

    原址:http://game.ceeger.com/forum/read.php?tid=4394#info 最近一直在和这些内容纠缠,把心得和大家共享一下: Unity里有两种动态加载机制:一是Re ...

  9. Unity动态加载3D模型

    Unity动态加载3D模型 在Unity中创建游戏对象的方法有 3 种: 第一种是将物体模型资源由 Project 视图直接拖曳到 Hierarchy 面板中: 第二种是在 Unity 3D 菜单 G ...

最新文章

  1. python subprocess_python subprocess
  2. linux读conf文件格式,CONF 文件扩展名: 它是什么以及如何打开它?
  3. java虚拟机类加载机制浅谈_浅谈Java虚拟机(三)之类加载机制
  4. 7-3 最小生成树-kruskal (10 分)(思路+详解+并查集详解+段错误超时解决)宝 Come
  5. 【项目管理】用LoC衡量程序员的工作效率是不科学的
  6. Python 数据科学入门教程:TensorFlow 目标检测
  7. Android 中文 API——android.widget合集(中)(50篇)(chm格式)
  8. ASP.NET MVC 学习笔记(1)
  9. 解决U盘插入我的电脑中不显示
  10. JSch连接不上Linux服务器,JSch链接linux服务器问题解决方案:Session.connect: java.io.IOException: End of IO Stream Read...
  11. 基于探索者串口更新字库笔记
  12. 诺顿防毒软件曝漏洞 任意下载运行恶意代码(转)
  13. 摄影知识——光圈和快门的组合
  14. 怀旧服ouf头像插件_魔兽世界怀旧服EUI插件 V9.0.1.6 官方版
  15. 187. 导弹防御系统
  16. linux python3安装proton_深度deepin系统中通过Lutris(wine、proton)运行逆水寒的方法 ......
  17. cookie详解,即什么是cookie。
  18. 数值分析:研究高次插值的龙格现象
  19. PTA解封日期C语言
  20. 微信小程序|使用小程序制作一个马赛克处理工具

热门文章

  1. 第一个神经网络代码分享
  2. mysql inno_mysql inno优化配置方法
  3. 百度图神经网络学习——day04:图神经网络算法(二)
  4. Python自然语言处理相,新词发现,主题模型,隐马尔模型词性标注,Word2Vec,情感分析...
  5. kafka 不同分区文件存储_Kafka 系列(二)文件存储机制与Producer架构原理怎样保证数据可靠性??...
  6. android hook 模拟点击_手把手讲解 Android Hook-实现无清单启动Activity
  7. win10无法修改mac地址_路由器无线MAC地址过滤如何设置
  8. leetcode求众数
  9. leetcode 链表1
  10. win7备份工具_u盘系统重装win7旗舰版详细图解教程