为了尽可能加快从网络加载场景,我们通常可以把场景先导出成 XML,把优先级高的资源优先加载并显示(地形等),把可以进入场景之后再加载的对象放到最后(比如场景里面的怪物等),本篇一部分代码引用自:http://www.xuanyusong.com/archives/1919,导出场景部分在原作者的代码基础进行了优化,并且整理成了更加方便,容易使用的类库。
先来搭建测试场景(测试场景来源网络),并整理场景中的对象,如图:
 
 
然后把场景中的对象都设置成预设,方便打包成 assetbundle 文件(如何打包预设请查看),如图:
 
 
接着我们编写把场景打包成 XML 的代码,取名 ExportSceneToXml.cs,大家可以先看这篇文章(http://www.xuanyusong.com/archives/1919),我在此基础上面进行了优化,全部代码如下:
复制代码代码如下:
</font>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)
					{
						// 判断是否是预设            
新闻热点
疑难解答