unity3d游戏开发之XML或JSON.docVIP

  • 4
  • 0
  • 约2.02万字
  • 约 20页
  • 2016-04-13 发布于浙江
  • 举报
unity3d游戏开发之XML或JSON

导出unity场景的所有游戏对象信息,一种是XML一种是JSON。本篇文章我们把游戏场景中游戏对象的、旋转、缩放、平移与Prefab的名称导出在XML与JSON中。然后解析刚刚导出的XML或JSON通过脚本把导出的游戏场景还原。在Unity官网上下载随便下载一个demo Project,如下图所示这是我刚刚在官网上下载的一个范例程序。? ?出自狗刨学习网 ? ?? ?? ?? ?? ?? ?? ?? ?? ?? ??? ? ?? ? 接着将层次视图中的所有游戏对象都封装成Prefab保存在资源路径中,这里注意一下如果你的Prefab绑定的脚本中有public Object 的话 ,需要在代码中改一下。。用 Find() FindTag()这类方法在脚本中Awake()方法中来拿,不然Prefab动态加载的时候无法赋值的,如下图所示,我把封装的Prefab对象都放在了Resources/Prefab文件夹下。? ? ?? ? OK,现在我们就需要编写我们的导出工具、在Project视图中创建Editor文件夹,接着创建脚本MyEditor 。如下图所示。? ?? ?? ?? ?? ?? ?? ?? ??? ? ?? ? 因为编辑的游戏场景数量比较多,导出的时候我们需要遍历所有的游戏场景,一个一个的读取场景信息。然后取得游戏场景中所有游戏对象的Prefab的 名称 旋转 缩放 平移。有关XML的使用请大家看我的上一篇文章:?Unity3D研究院之使用 C#合成解析XML与JSON(四十一)代码中我只注释重点的部分,嘿嘿。 ? ?? ? MyEditor.cs using UnityEngine; using System.Collections; using UnityEditor; using System.Collections.Generic; using System.Xml; using System.IO; using System.Text; using LitJson; public class MyEditor : Editor { ? ? //将所有游戏场景导出为XML格式 ? ? [MenuItem (GameObject/ExportXML)] ? ? static void ExportXML () ? ? { ? ?? ???string filepath = Application.dataPath + @/StreamingAssets/my.xml; ? ?? ???if(!File.Exists (filepath)) ? ?? ???{ ? ?? ?? ?? ?File.Delete(filepath); ? ?? ???} ? ?? ???XmlDocument xmlDoc = new XmlDocument(); ? ?? ???XmlElement root = xmlDoc.CreateElement(gameObjects); ? ?? ???//遍历所有的游戏场景 ? ?? ???foreach (UnityEditor.EditorBuildSettingsScene S in UnityEditor.EditorBuildSettings.scenes) ? ?? ???{ ? ?? ?? ?? ?//当关卡启用 ? ?? ?? ?? ?if (S.enabled) ? ?? ?? ?? ?{ ? ?? ?? ?? ?? ? //得到关卡的名称 ? ?? ?? ?? ?? ? string name = S.path; ? ?? ?? ?? ?? ? //打开这个关卡 ? ?? ?? ?? ?? ? EditorApplication.OpenScene(name); ? ?? ?? ?? ?? ? XmlElement scenes = xmlDoc.CreateElement(scenes); ? ?? ?? ?? ?? ? scenes.SetAttribute(name,name); ? ?? ?? ?? ?? ? foreach (GameObject obj in Object.FindObjectsOfType(typeof(GameObject))) ? ?? ?? ?? ?? ? { ? ?? ?? ?? ?? ?? ???if (obj.transform.parent == null) ? ?? ?? ?? ?? ?? ???{ ? ?? ?? ?? ?? ?? ?? ?? ? XmlElement gameObject = xmlDoc.CreateElement(gameObjects); ? ?? ?? ?? ?? ?? ?? ?? ? ga

文档评论(0)

1亿VIP精品文档

相关文档