Unity利用Xml和Json保存场景


尊重原创,转载请注明出处,谢谢!

http://blog.csdn.net/y1196645376/article/details/52549082


之前已经简单介绍了XML和JSON的基本使用方法。这里我就介绍一个例子来对XML和JSON进行实战应用 --------- 场景的保存和热更。

提前Ps :   所讲工程内容最后都会给出源码地址。


1.首先你得有一个场景。这个迷宫地形我搭了好久。。


可以看到地图中有个环境Env,人物Player,灯光Light,UGUI事件系统EventSystem,画布Canvas。Init不用管,先删掉。我们把这几个物品全部做成Prefab。我放在了Prefab的文件夹里面。

值得注意的是,如果这些Prefab或者其子物体中身上所挂脚本有pubulic变量添加的是其他物体或者组件的引用需要将这些变量全部私有化然后放到Awake函数里面通过Game.FindWithTag()或者Transform.Find等函数动态获取。

当然,以上的解决方案可能让你很不习惯,没有更好的解决方法了吗?当然有,这个教程中我们只是对资源设置了Prefab。后面我们用篇文章来讲述AssetBundle的使用,而这个技术不仅实现了资源的打包,而且很好的处理了这些资源依赖关系。这也就是后话了。。。这篇文章不涉及。


2.做完以上步骤之后,我们对资源的处理就完毕了,剩下我们就来编写代码实现对场景信息记录。大概的思路就是:读取所有场景信息,然后对于每个场景遍历其所有的Prefab物体,然后记录其坐标,旋转,大小。( 注意:下面代码中涉及到LitJsond包的使用,请将LitJson.dll放到工程的Plugin目录下 )

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System.Xml;
using System.IO;
using System.Text;
using LitJson;
public class ScencePack : 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");
                        gameObject.SetAttribute("name", obj.name);

                        gameObject.SetAttribute("asset", obj.name + ".prefab");
                        XmlElement transform = xmlDoc.CreateElement("transform");
                        XmlElement position = xmlDoc.CreateElement("position");
                        XmlElement position
  • 7
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 9
    评论
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值