1、打包场景(转)
把场景文件打包成 .unity3d 后缀的文件。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class PackAB {
#if UNITY_EDITOR
[MenuItem("Custom Editor/Create Scene")]
static void CreateSceneALL()
{
//清空一下缓存
Caching.ClearCache();
//获得用户选择的路径的方法,可以打开保存面板(推荐)
string Path = EditorUtility.SaveFilePanel("保存资源", "SS", "" + "Scene_02", "unity3d");
//string Path = Application.dataPath + "/Scene_02.unity3d";
//另一种获得用户选择的路径,默认把打包后的文件放在Assets目录下
//string Path = Application.dataPath + "/MyScene.unity3d";
//选择的要保存的对象
string[] levels = { "Assets/Scenes/Scene_02.unity" };
//打包场景
BuildPipeline.BuildPlayer(levels, Path, BuildTarget.StandaloneWindows64, BuildOptions.BuildAdditionalStreamedScenes);
// 刷新,可以直接在Unity工程中看见打包后的文件
AssetDatabase.Refresh();
}
#endif
}
2、用WWW下载刚才打包的.unity3d文件并加载出来。
using UnityEngine.SceneManagement;
using UnityEngine;
using System.Collections;
public class SceneCreate : MonoBehaviour
{
public GameObject prefab1;
public Transform trans;
void Start()
{
//加载.unity3d后缀的场景文件
StartCoroutine("LoadScene");
}
private IEnumerator LoadScene()
{
WWW download = WWW.LoadFromCacheOrDownload("file://" + Application.dataPath + "/Scene_02.unity3d", 1);
yield return download;
var bundle = download.assetBundle;
AsyncOperation ao = SceneManager.LoadSceneAsync("Scene_02", LoadSceneMode.Additive); //不需要在build and settings窗口中设置好,这里可以直接用
yield return ao;
Scene newScene2 = SceneManager.GetSceneByName("Scene_02"); //获取刚才加载的场景
SceneManager.SetActiveScene(newScene2); //把场景激活
GameObject newObj = GameObject.Instantiate(prefab1, trans.position, trans.rotation); //在场景中实例化prefab
}
}