Unity使用AssetDatabase编辑器资源管理

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq826364410/article/details/81916104

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()来保存修改。

猜你喜欢

转载自blog.csdn.net/qq826364410/article/details/81916104