Unity 动态记载Prefab

Unity动态记载Prefab

  1. 第一种方法,从Resources文件夹读取Prefab
    Assets/Resources是Unity中的一个特殊文件夹,放在这个文件夹里的资源包括Prefab可以被代码动态加载。
GameObject Prefab = (GameObject)Resources.Load("Prefabs/Character");
Instantiate(Prefab);
  1. 第二种方法,绝对路径读取Prefab
    这种方法仅限Editor模式使用,在制作插件的时候会经常使用的方法。
GameObject gb = AssetDatabase.LoadAssetAtPath("Assets/Prefabs/Character.prefab", typeof(GameObject)) as GameObject; //该函数返回一个object,需要强转为GameObject,第一个参数为完整绝对路径,第二个参数为Prefab名  
Instantiate(gb);
  1. 第三种方法,把Prefab打包成AssetBundle并且使用AssetBundle相关API动态加载
    1)在Inspector面板中把prefab资源打包。
    2)编写AssetBundle生成工具
    Plugins/Editor也是Unity中的一个特殊文件夹,在Plugins下的脚本的编译优先级高于普通脚本。
    在Asset下创建文件夹Plugins,再在Plugins下创建文件夹Editor,在Plugins/Editor下创建脚本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);
    }
}

3)创建脚本加载Prefab
创建加载脚本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);
    }
}

原文:https://blog.csdn.net/haowenlai2008/article/details/82807019

猜你喜欢

转载自blog.csdn.net/a834595603/article/details/90109044
今日推荐