读书人

unity3d 自定义资源包运用

发布时间: 2013-03-16 11:51:46 作者: rapoo

unity3d 自定义资源包使用

1.创建资源包:

public class Sript_01 : MonoBehaviour

{

[MenuItem ("自定义资源包/创建资源包")]

static void ExecCreateAssetBunldes()

{

//设置保存资源包的根路径

string targetDir = Application.dataPath + "/AssetBundles";

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

//创建一个目录,用于保存资源包

if(!Eirectory.Exists(targetDir))

{

Directory.CreateDirectory(targetDir);

}

for(int i=0;i<selectedAsset.Length;i++)

{

//生成资源包的完整路径

string filepath = targetDir + "/" + SelectedAsset[i].name + ".unity3d";

//根据路径判断资源包文件是否存在

if(File.Exists(filePath))

{

File.Delete(filePath);

}

//生成新的资源包文件

if(BuildPipeline.BuildAssetBundle(SelectedAsset[i],null,filePath,BuildAssetBundleOptions.CollectDependencies))

{

Debug.Log(“资源包生成成功”);

AssetDatabase.Refresh();

}

else

Debug.Log("资源包文件生成失败");

}

}

}

}

Note: This is an editor class. To use it you have to place your script inAssets/Editor inside your project folder. Editor classes are in the UnityEditor namespace so for C# scripts you need to add "using UnityEditor;" at the beginning of the script.

2.下载资源包

IEnumerator loadBundleMat(string name)

{

Material mat;

//资源在本机的路径

WWW date = new WWW("file://" + Application.dataPath + "/AssetBundles/" + name + "./unity3d");

//等待下载完成

yield return date;

//将下载得到的资源强制转换成材质资源

mat = (Material)date.assetBundle.mainAsset;

//更换为下载的资源

renderer.material = mat;

//释放资源对象

date.assetBundle.Unload(false);

}

IEnumerator loadBundleObject (string name)

{

WWW date = new WWW("file://" + Application.dataPath + "AssetBundles/" + name + ".unity3d");

//等待下载完成,并且克隆游戏对象,

yield return Instantiate(date.assetbundle.mainAsset);

//释放资源对象

date.assetbundle.Unload(false);

}

注释: 资源包下载完成后,资源文件将保持在assetBundle.mainAsset 对象中,接着使用该对象即可。由于连续下载资源包对象会出错,所以下载完资源后需要手动释放对象。

读书人网 >移动开发

热点推荐