• 【Unity】使用AssetDatabase编辑器资源管理


    最近参考了各位大神的资源,初步学习了Unity的资源管理模式,包括在编辑器管理(使用AssetDatabase)和在运行时管理(使用Resources和AssetBundle)。在此简单总结编辑器模式下的资源管理方法,方便自己回顾。


    ① 加载/卸载资源

    using UnityEngine;
    using System.Collections;
    #if UNITY_EDITOR
    using UnityEditor; // 这个文件在手机上没有,需要使用条件编译
    #endif
    
    public class TestLoadAsset : MonoBehaviour {
    
        void Start () {
    #if UNITY_EDITOR
            // 加载资源
            Texture2D image = AssetDatabase.LoadAssetAtPath("Assets/Images/1.jpg", typeof(Texture2D)) as Texture2D;
            // 使用资源
            Debug.Log(image.name);
            // 卸载资源:注意,卸载方法是在Resources类中
            Resources.UnloadAsset(image);
            // 调用GC来清理垃圾,资源不是立刻就被清掉的
            Debug.Log(image);
    #endif
        }
    }

    需要注意的是,调用Resources.UnloadAsset()来清理资源时,只是标记该资源需要被GC回收,但不是立刻就被回收的,下一行的Debug.Log依然能看到该资源的引用不是Null。


    ② 创建资源

    using UnityEngine;
    using System.Collections;
    #if UNITY_EDITOR
    using UnityEditor; // 这个文件在手机上没有,需要使用条件编译
    #endif
    
    // 创建资源
    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资源。
    这里写图片描述
    需要注意的是,无法直接创建一个资源,可以先加载一个现有的资源作为模版,或者像官方文档中的例子那样先New一个模板出来。


    ③ 修改资源

    using UnityEngine;
    using System.Collections;
    #if UNITY_EDITOR
    using UnityEditor; // 这个文件在手机上没有,需要使用条件编译
    #endif
    
    public class TestModifyAsset : MonoBehaviour {
    
        // Use this for initialization
        void Start () {
    #if UNITY_EDITOR
            // 加载资源
            Material mat = AssetDatabase.LoadAssetAtPath("Assets/Materials/New Material.mat", typeof(Material)) as Material;
            // 修改资源
            mat.color = Color.blue;
            // 通知编辑器有资源被修改了
            EditorUtility.SetDirty(mat);
            // 保存所有修改
            AssetDatabase.SaveAssets();
    #endif
        }
    }

    运行脚本后,会发现New Material.mat这个材质资源的颜色被永久改为了蓝色。
    这里写图片描述
    需要注意的是,在对资源做了任何修改后,需要通知编辑器有资源已被修改,使用 EditorUtility.SetDirty()函数来标记已被修改的资源,然后调用AssetDatabase.SaveAssets()来保存修改。

  • 相关阅读:
    数组中出现次数超过一半的数字
    Trie字典树算法
    字符串匹配算法 之 基于DFA(确定性有限自动机)
    实现栈最小元素的min函数
    有关有环链表的问题
    浅谈C中的malloc和free
    undefined reference to 'pthread_create'问题解决
    用两个栈实现队列
    resf规范
    单例模式
  • 原文地址:https://www.cnblogs.com/guxin/p/unity-how-to-use-assetdatabase.html
Copyright © 2020-2023  润新知