[Unity基础]打包与读取AssetBundle

原文链接:http://www.xuanyusong.com/archives/2405


1.打包prefab

using UnityEngine;
using System.Collections;
using UnityEditor;

//选择的物体放在不同的AB
public class CreateAB_Respectively : MonoBehaviour {

    [MenuItem("Custom Editor/Create AssetBunldes Main")]
    static void CreateAssetBunldesMain()
    {
        //获取在Project视图中选择的所有游戏对象
        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);

        //遍历所有的游戏对象
        foreach (Object obj in SelectedAsset)
        {
            string sourcePath = AssetDatabase.GetAssetPath(obj);
            //本地测试:建议最后将Assetbundle放在StreamingAssets文件夹下,如果没有就创建一个,因为移动平台下只能读取这个路径
            //StreamingAssets是只读路径,不能写入
            //服务器下载:就不需要放在这里,服务器上客户端用www类进行下载。
            string targetPath = Application.dataPath + "/StreamingAssets/" + obj.name + ".assetbundle";
            if (BuildPipeline.BuildAssetBundle(obj, null, targetPath, BuildAssetBundleOptions.CollectDependencies))
            {
                Debug.Log(obj.name + "资源打包成功");
            }
            else
            {
                Debug.Log(obj.name + "资源打包失败");
            }
        }
        //刷新编辑器
        AssetDatabase.Refresh();
    }
}

using UnityEngine;
using System.Collections;
using UnityEditor;

//选择的物体放在同一个AB
public class CreateAB_Together : MonoBehaviour {

    [MenuItem("Custom Editor/Create AssetBunldes ALL")]
    static void CreateAssetBunldesALL()
    {
        Caching.CleanCache();

        string Path = Application.dataPath + "/StreamingAssets/ALL.assetbundle";

        Object[] SelectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);

        foreach (Object obj in SelectedAsset)
        {
            Debug.Log("Create AssetBunldes name :" + obj);
        }

        //这里注意第二个参数就行
        if (BuildPipeline.BuildAssetBundle(null, SelectedAsset, Path, BuildAssetBundleOptions.CollectDependencies))
        {
            AssetDatabase.Refresh();
        }
        else
        {
        }
    }
}

2.打包场景

using UnityEngine;
using System.Collections;
using UnityEditor;

//打包场景
//把11.unity场景文件打包到MyScene.unity3d文件中,
//所以在解包的时候也应当是先解开MyScene.unity3d,然后在去加载11.unity场景,
//无需在ProjectSetting中注册新场景。

public class CreateAB_Scene : MonoBehaviour {

	[MenuItem("Custom Editor/Create Scene")]
	static void CreateSceneALL ()
	{
		//清空一下缓存
		Caching.CleanCache();
        string Path = Application.dataPath + "/StreamingAssets/" + "/MyScene.unity3d";
		string[] levels = {"Assets/TestAB/11.unity"};
    	//打包场景
        BuildPipeline.BuildStreamedSceneAssetBundle(levels,Path,BuildTarget.StandaloneWindows64,BuildOptions.BuildAdditionalStreamedScenes);
    	//BuildPipeline.BuildPlayer( levels, Path, BuildTarget.WebPlayer, BuildOptions.BuildAdditionalStreamedScenes);
		AssetDatabase.Refresh ();
	}
}

3.读出AssetBundle

using UnityEngine;
using System.Collections;
 
public class RunScript : MonoBehaviour {

	    //不同平台下StreamingAssets的路径是不同的,这里需要注意一下。
	    public static readonly string PathURL =
#if UNITY_ANDROID
		"jar:file://" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE
		Application.dataPath + "/Raw/";
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
	"file://" + Application.dataPath + "/StreamingAssets/";
#else
        string.Empty;
#endif
 
	void OnGUI()
	{
		if(GUILayout.Button("Main Assetbundle"))
		{
            StartCoroutine(LoadMainGameObject(PathURL + "Cube.assetbundle"));
            StartCoroutine(LoadMainGameObject(PathURL + "Cube2.assetbundle"));
		}
		if(GUILayout.Button("ALL Assetbundle"))
		{
			StartCoroutine(LoadALLGameObject(PathURL + "ALL.assetbundle"));
		}
        if (GUILayout.Button("Open Scene"))
        {
            StartCoroutine(LoadScene());
        }
	}
 
	//读取一个资源
	private IEnumerator LoadMainGameObject(string path)
	{
        WWW bundle = WWW.LoadFromCacheOrDownload(path, 5);
        yield return bundle;
        yield return Instantiate(bundle.assetBundle.mainAsset);
        bundle.assetBundle.Unload(false);
	}
 
	//读取全部资源
	private IEnumerator LoadALLGameObject(string path)
	{
        WWW bundle = WWW.LoadFromCacheOrDownload(path, 5);
		yield return bundle;
 
		//通过Prefab的名称把他们都读取出来
        Object obj0 = bundle.assetBundle.Load("Cube");
        Object obj1 = bundle.assetBundle.Load("Cube2");
 
		//加载到游戏中	
		yield return Instantiate(obj0);
		yield return Instantiate(obj1);
		bundle.assetBundle.Unload(false);
	}

    //读取场景
	private IEnumerator LoadScene()
	{
        WWW download = WWW.LoadFromCacheOrDownload("file://" + Application.dataPath + "/StreamingAssets/" + "/MyScene.unity3d", 1);
		yield return download;
		var bundle = download.assetBundle;
  		Application.LoadLevel ("11");
	}
}

你可能感兴趣的:(Assetbundle)