unity

Unity 资源管理与AssetBundle详解

2018-03-22  本文已影响34人  柚梨柚梨

什么是资源(Asset)

http://blog.csdn.net/u014230923/article/details/51433455
Unity常用的资源大概有3类:

  1. 纯资源(material,texture,shader,audio ……)这些资源不能直接拖到场景里使用。
  2. 预置(prefab),这种资源需要实例化instantiate之后才能使用
  3. scene也是一种资源

还有一些平时不太关注的:脚本对象,文本文件,unity自己内置的资源(像新建粒子时的默认材质之类的),这些也是资源。

资源管理

http://blog.csdn.net/qq_18995513/article/details/51955609
Unity的资源管理模式,包括在编辑器管理(使用AssetDatabase)和在运行时管理(使用Resources和AssetBundle)。

1. 编辑器管理: AssetDatabase

在编辑器内加载卸载资源,并不能在游戏发布时使用,它只能在编辑器内使用。但是,它加载速度快,效率高,适合在测试时使用

因为只能在编辑器使用,要加个宏防止报错:

#if UNITY_EDITOR
    using UnityEditor;
#endif

加载(Load) Asset

#if UNITY_EDITOR
            assetInfo.asset = UnityEditor.AssetDatabase.LoadAssetAtPath(BundleUtils.RealPath(assetPath), type);
            assetInfo.assetName = assetPath;
            assetInfo.type = type;
            assets[assetPath] = assetInfo;
#else

卸载(Unload) Asset

https://docs.unity3d.com/ScriptReference/Resources.UnloadAsset.html

 Resources.UnloadAsset(asset);

Unloads assetToUnload from memory.

This function can only be called on Assets that are stored on disk.

If there are any references from game objects in the scene to the asset and it is being used then Unity will reload the asset from disk as soon as it is accessed.

需要注意的是,调用Resources.UnloadAsset()来清理资源时,只是标记该资源需要被GC回收,但不是立刻就被回收的。需要调用

System.GC.Collect();

使用脚本创建Asset

// 创建资源
public class TestCreateAsset : MonoBehaviour {

    void Start () {
#if UNITY_EDITOR
        // 加载资源
        Material mat = AssetDatabase.LoadAssetAtPath("Assets/Materials/New Material.mat", typeof(Material)) as Material;
        // 以mat为模板创建mat2
        Material mat2 = Object.Instantiate<Material>(mat);
        // 创建资源
        AssetDatabase.CreateAsset(mat2, "Assets/Materials/1.mat");
        // 刷新编辑器,使刚创建的资源立刻被导入,才能接下来立刻使用上该资源
        AssetDatabase.Refresh();
        // 使用资源
        Debug.Log(mat2.name);
#endif
    }
}

运行脚本后,会发现在编辑器里就会出现:Project视窗中多了一个刚创建的1.mat资源。

修改Asset

具体见上面链接

2. 在运行时管理:使用Resources[1]

Resources.Load就是从一个缺省打进程序包里的AssetBundle里加载资源,而一般AssetBundle文件需要你自己创建,运行时 动态加载,可以指定路径和来源的。

3. 在运行时管理:使用AssetBundle[2]

存储结构存储结构

注意下图有一些错误需要更新:

AssetBundle的内存占用AssetBundle的内存占用 [4]

各种加载和初始化:

各种释放


  1. Unity官方文档 Resources: https://docs.unity3d.com/540/Documentation/ScriptReference/Resources.html

  2. Reference: http://www.cnblogs.com/88999660/archive/2013/03/15/2961663.html

  3. https://docs.unity3d.com/ScriptReference/AssetBundle.LoadFromFile.html

  4. http://blog.csdn.net/u011926026/article/details/70155178

  5. Unity官方文档 Object.DontDestroyOnLoad: https://docs.unity3d.com/ScriptReference/Object.DontDestroyOnLoad.html

  6. Unity官方文档 Destroy: https://docs.unity3d.com/ScriptReference/Object.Destroy.html

上一篇下一篇

猜你喜欢

热点阅读