首先得用ExportResourceBySelection这个类打包预设名字为:Sphere.unity3d 我的电脑上的保存路径为:file:///D:/MyUnity4.6Project/Test/Assets/Resources/prefab/
要选中预设Sphere,右键Build AssetBundle From Selection,保存为:Sphere.unity3d
public class ExportResourceBySelection
{
[MenuItem("Assets/Build AssetBundle From Selection")]
static void ExportResource()
{
string path = EditorUtility.SaveFilePanel ("Save Resource", "", "New Resource", "unity3d");//打包成.unity3d格式,根据需要你可以是assetbundle格式的,默认名字是:New Resource
if (path.Length != 0)
{
Object[] selections = Selection.GetFiltered(typeof(Object), SelectionMode.DeepAssets);
BuildPipeline.BuildAssetBundle(Selection.activeObject, selections, path, BuildAssetBundleOptions.CollectDependencies | BuildAssetBundleOptions.CompleteAssets, BuildTarget.StandaloneWindows);
AssetDatabase.Refresh();
}
}
}
如何动态加载prefab实例呢
通过下面这个类:下面采用了两种方式,一个是Resources.LoadAssetAtPath(),一个是 AssetBundle的 new WWW()
/// <summary>
/// 动态加载Prefab实例
/// </summary>
public class LoadPrefab : MonoBehaviour
{
/// <summary>
/// 加载方法枚举
/// </summary>
public enum LoadMethod
{
Resources,
AssetBundle
}
/// <summary>
/// 加载方法
/// </summary>
public LoadMethod method;
// Use this for initialization
private void Start()
{
if (method == LoadMethod.Resources)
LoadPrefabByResources();
else
LoadPrefabByAssetBundle();
}
// 通过Resources.LoadAtPath方法动态加载Prefab
private void LoadPrefabByResources()
{
Object prefab = Resources.LoadAssetAtPath("Assets/Prefabs/Cube.prefab", typeof(GameObject));//Resources.LoadAssetAtPath加载unity工程下指定目录的文件,该
//目录可以是unity目录下任意的,而Resources.Load()的局限性是必须是:Resources路径下的文件或者子文件
GameObject cube = (GameObject)Instantiate(prefab);
cube.transform.parent = transform;
}
// 通过AssetBundle方式动态加载Prefab
private void LoadPrefabByAssetBundle()
{
//string path = "http://192.168.12.75/Sphere.unity3d";//加载服务器端的文件
string path = "file:///D:/MyUnity4.6Project/Test/Assets/Resources/prefab/Sphere.unity3d";//加载本机磁盘路径的文件
StartCoroutine(DownLoadPrefab(path));
}
// 下载Prefab文件
private IEnumerator DownLoadPrefab(string path)
{
Debug.Log(Application.persistentDataPath);
WWW www = new WWW(path);
yield return www;
if (www.isDone)
{
GameObject sphere = (GameObject)Instantiate(www.assetBundle.mainAsset);
sphere.transform.parent = transform;
yield return sphere;
www.assetBundle.Unload(false);
}
}
}