Unity学习笔记(5):动态加载Prefab

第一种方法,从Resources文件夹读取Prefab
Assets/Resources文件夹是Unity中的一个特殊文件夹,在博主当前的认知里,放在这个文件夹里的Prefab可以被代码动态加载
直接上代码

GameObject Prefab = (GameObject)Resources.Load("Prefabs/Character");
Instantiate(Prefab);

第二种方法,绝对路径读取Prefab
这种方法仅限Editor模式使用,在制作插件的时候会经常用到

GameObject gb = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Character.prefab", typeof(GameObject)) as GameObject;
Instantiate(gb)

Resources.Load函数返回一个object对象,第一个参数为以Resources为根目录,目标Prefab的路径,第二个参数为Prefab的名字,最后将这个object对象强转成(GameObjcet)就可以获得Prefab了
第三种方法,把Prefab打包成AssetBundle并且使用AssetBundle相关API动态加载

1.首先在资源管理器中找到你想打包的Prefab,找到Inspector页面下面的Asset_Labels,打开
在这里插入图片描述
发现AssetBundle后面有两个选项,第一个选项为AssetBundle的包名,第二个选项为包的后缀名,自定义你想要的包名和后缀,将想要打在一个包的资源的AssetBundle的包名和后缀设置成一样的
2.编写AssetBundle生成工具
在Asset下创建文件夹Plugins,再在Plugins下创建文件夹Editor,在Plugins/Editor下创建脚本CreateAssetBundles.cs
Plugins/Editor和Resource一样是特殊路径,在Plugins下的脚本的编译优先级高于普通脚本。

CreateAssetBundles.cs:

using UnityEditor;
using System.IO;

public class CreateAssetBundles {
    //设定AssetBundle的储存路径
    static string AssetbundlePath = "Assets" + Path.DirectorySeparatorChar + "assetbundles" + Path.DirectorySeparatorChar;
    //编辑器扩展
    [MenuItem("Assets/Build AssetBundle")]
    static void BuildAssetsBundles()
    {
        //创建路径
        if (Directory.Exists(AssetbundlePath) == false)
        {
            Directory.CreateDirectory(AssetbundlePath);
        }
        //使用LZMA算法打包
        BuildPipeline.BuildAssetBundles(AssetbundlePath, BuildAssetBundleOptions.None, BuildTarget.StandaloneWindows64);
    }
}

BuildPipeline.BuildAssetBundles的第二个参数是打包的压缩方式
有三个可选参数
BuildAssetBundleOptions.None LZMA算法压缩,压缩包小,加载慢
BuildAssetBundleOptions.UncompressedAssetBundle; 不压缩,包大,加载快
BuildAssetBundleOptions.ChunkBasedCompression LZ4压缩,压缩率比LZMA低,可以加载指定资源不用解压全部

保存
回到Unity Editor,点击Assets可以看到最下面出现了Build AssetBundle选项,点击Build AssetBundle,打包
在这里插入图片描述
打包完成后可以在刚刚设置的AssetBundle所在路径找到几个文件
在这里插入图片描述
这几个文件具体是什么暂时不讨论
3.加载Prefab
创建脚本AssetBundleLoader.cs
AssetBundleLoader.cs:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AssetBundleLoader
{
    //参数1是AssetBundle的路径,参数2是资源的名称
	public static GameObject LoadAssetBundle(string Path, string Name)
    {
        //1.卸载数据,如果有某个系统来管理加载好的数据就不要加下面这句了
        AssetBundle.UnloadAllAssetBundles(true);

        //2.加载数据
        AssetBundle ab = AssetBundle.LoadFromFile(Path);

        return ab.LoadAsset<GameObject>(Name);
    }
}

可以通过AssetBundleLoader.LoadAssetBundle(string, string)来加载Prefab等资源,关于这个函数要不要先卸载AssetBundle,这取决于你的框架是否只需要加载一次这个包,并且有一个管理这些资源的系统,我这种做法无疑是降低效率的(其实就是懒得再搭个系统),根据实际情况用不同的方式来加载AssetBundle吧

posted @ 2018-10-07 17:26  凌夜霜  阅读(3938)  评论(0编辑  收藏  举报