您的位置:首页 > 移动开发 > Unity3D

unity3d之Assetbundle打包预设Prefab和场景Scene

2017-03-02 22:32 525 查看
新建工程,在Assets下新建Scenes文件夹存放场景文件,新建三个Cube,分别命名为Cube、Cube1、Cube2并保存为三个预设,保存新建在ReanAssetbundle.cs脚本,脚本内容如下:

using UnityEngine;

using System.Collections;

public class ReanAssetbundle : MonoBehaviour {

    
// Use this for initialization
void Start () {

        
}

    

    

// Update is called once per frame
void Update () {

}

    //不同平台下StreamingAssets的路径是不同的,这里需要注意一下。  

    public static readonly string m_PathURL =

#if UNITY_ANDROID  

        "jar:file://" + Application.dataPath + "!/assets/";  

#elif UNITY_IPHONE  

        Application.dataPath + "/Raw/";  

#elif UNITY_STANDALONE_WIN || UNITY_EDITOR

 "file://" + Application.dataPath + "/AssetBundleLearn/";

#else  

        string.Empty;  

#endif

    void OnGUI()

    {

        if (GUILayout.Button("加载分开打包的Assetbundle"))

        {

            StartCoroutine(LoadGameObjectPackedByThemselves(m_PathURL + "Cube.assetbundle"));

            StartCoroutine(LoadGameObjectPackedByThemselves(m_PathURL + "Cube1.assetbundle"));

            StartCoroutine(LoadGameObjectPackedByThemselves(m_PathURL + "Cube2.assetbundle"));

        }

        if (GUILayout.Button("加载打包在一起的Assetbundle"))

        {

            StartCoroutine(LoadGameObjectPackedTogether(m_PathURL + "Together.assetbundle"));

        }        

    }

    //单独读取资源  

    private IEnumerator LoadGameObjectPackedByThemselves(string path)

    {

        WWW bundle = new WWW(path);

        yield return bundle;

        //加载  

        yield return Instantiate(bundle.assetBundle.mainAsset);

        bundle.assetBundle.Unload(false);

    }

    IEnumerator LoadGameObjectPackedTogether(string path)

    {

        WWW bundle = new WWW(path);

        yield return bundle;

        Object one = bundle.assetBundle.Load("Cube");

        Object two = bundle.assetBundle.Load("Cube1");

        Object three = bundle.assetBundle.Load("Cube2");

        //加载  

        yield return Instantiate(one);

        yield return Instantiate(two);

        yield return Instantiate(three);

        bundle.assetBundle.Unload(false);

    }

}

把此脚本挂在Main Camera上,将当前场景保存为Cube.unity,保存到Scenes文件夹下。

Assets文件夹下新建Editor文件夹,在Editor下新建ExportAssetBundles.cs脚本,脚本的内容为

using UnityEngine;
using UnityEditor;
using System.Collections;
 
public class ExportAssetBundles :EditorWindow
{
   ///<summary> 

   ///将选中的预制分别打包 
   ///</summary> 

    [MenuItem("AssetBundleDemo/CreateAssetBundles By themselves")]
   static void CreateAssetBundleThemelves()
    {
       //获取要打包的对象(在Project视图中) 
       Object []selects =
Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
       //遍历选中的对象 
       foreach (Objectobjin selects)
        {      

                      //在Assets下新建AssetBundleLearn文件夹,存放打包的预设   
           stringtargetPath =
Application.dataPath +"/AssetBundleLearn/" +obj.name +
".assetbundle";//文件的后缀名是assetbundle和unity都可以 
           if (BuildPipeline.BuildAssetBundle(obj,null,targetPath,BuildAssetBundleOptions.CollectDependencies))
            {
 
               Debug.Log(obj.name +"ispacked successfully!");
            }
           else
            {
               Debug.Log(obj.name +"ispacked failly!");
            }
        }
       //刷新编辑器(不写的话要手动刷新,否则打包的资源不能及时在Project视图内显示) 
       AssetDatabase.Refresh();
    }

     ///<summary> 
   ///将选中的预制一起打包 
   ///</summary>
    [MenuItem("AssetBundleDemo/CreateAssetBundles Together")]
   static void CreateAssetBundleTogether()
    {
       //要打包的对象 
        Object[]selects =Selection.GetFiltered(typeof(Object),SelectionMode.DeepAssets);
       //要打包到的路径 
       stringtargetPath =
Application.dataPath +"/AssetBundleLearn/Together.assetbundle";
       if (BuildPipeline.BuildAssetBundle(null,selects,
targetPath,BuildAssetBundleOptions.CollectDependencies))
        {
           Debug.Log("Packedsuccessfully!");
 
        }
       else
        {
           Debug.Log("Packedfailly!");
        }
       //刷新编辑器(不写的话要手动刷新) 
       AssetDatabase.Refresh();
    }
 
 
     ///<summary> 
   ///打包场景 
   ///</summary>
    [MenuItem("CustomEditor/Create Scene")]
   static void CreateSceneALL()
    {
       //清空一下缓存
       Caching.CleanCache();
//打包后的资源名为MyScene.unity3d
       stringPath =
Application.dataPath +"/MyScene.unity3d";
//被打包的场景名字为Cube.unity
       string[]levels = {
"Assets/Scenes/Cube.unity"};
       //打包场景
       BuildPipeline.BuildPlayer(levels,Path,BuildTarget.WebPlayer,
BuildOptions.BuildAdditionalStreamedScenes);
       AssetDatabase.Refresh();
    }
}

ExportAssetBundles 脚本完成后,会在unity的菜单栏中出现以上两个菜单,AssetBundleDemo/Create AssetBundles By themselves和AssetBundleDemo/Create AssetBundles Together,选中三个cube的预设,,点击第一个菜单会分别创建三个资源,再点击第二个菜单会将三个预设存入一个资源包中,资源包会保存在AssetBundleLearn文件夹下,运行程序,分别点击"加载分开打包的Assetbundle"和"加载打包在一起的Assetbundle"按钮,会创建被打包的资源。

隐藏掉Main Camera上的ReanAssetbundle脚本,点击Custom Editor/CreateScene菜单,会在Assets下创建一个MyScene.unity3d资源文件,新建一个Scene场景,命名为Load.unity,拖入一个空的GameObject,新建一个脚本LoadScene.cs,内容如下:

using UnityEngine;

using System.Collections;

public class LoadScene : MonoBehaviour {

    private string url;

    private string assetname;
// Use this for initialization
void Start () {

        url = "file://" + Application.dataPath + "/MyScene.unity3d";
}

// Update is called once per frame
void Update () {

}

    IEnumerator Download()

    {

        WWW www = new WWW(url);

        yield return www;

        if (www.error != null)

        {

            Debug.Log("下载失败");

        }

        else

        {

            AssetBundle bundle = www.assetBundle;

            Application.LoadLevel("Cube");

            // AssetBundle.Unload(false),释放AssetBundle文件内存镜像,不销毁Load创建的Assets对象

            // AssetBundle.Unload(true),释放AssetBundle文件内存镜像同时销毁所有已经Load的Assets内存镜像

            bundle.Unload(false);

        }

        // 中断正在加载过程中的WWW

        www.Dispose();

    }

    void OnGUI()

    {        

        if (GUILayout.Button("加载打包的场景"))

        {

            StartCoroutine(Download());

        }

    }

}

将此脚本挂在空的GameObject上,运行程序,点击会加载已保存的MyScene.unity3d资源包。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity3d 打包