前言
unity中有個類驹溃,叫做AssetDatabase,這是一個在編輯器(Editor)下使用的一個類幻妓,是一個允許您訪問工程中資源的API。這個類包含了查找、加載安拟、創(chuàng)建、刪除和修改資源等。這個類僅適用于編輯器狀態(tài)下蝌矛。
導(dǎo)入資源
unity不僅僅可以通過拖拽導(dǎo)入資源,還可以通過腳本導(dǎo)入資源票唆,代碼如下:
sing UnityEngine;
using UnityEditor;
public class ImportAsset
{
[MenuItem ("AssetDatabase/ImportExample")]
static void ImportExample ()
{
AssetDatabase.ImportAsset("資源路徑+資源名字", ImportAssetOptions.Default);
}
}
加載資源
加載資源有很多API,大家可以參考API手冊進行操作屹徘,加載API包含:
AssetDatabase.LoadAssetAtPath
AssetDatabase.LoadMainAssetAtPath
AssetDatabase.LoadAllAssetRepresentationsAtPath
AssetDatabase.LoadAllAssetsAtPath
參考下面案例進行使用:
using UnityEngine;
using UnityEditor;
public class ImportAsset
{
[MenuItem ("AssetDatabase/LoadAssetExample")]
static void ImportExample ()
{
Texture2D t = AssetDatabase.LoadAssetAtPath("Assets/Textures/texture.jpg", typeof(Texture2D)) as Texture2D;
}
}
操作文件
更改提交至數(shù)據(jù)庫
這里提前聲明一下走趋,修改完資源后應(yīng)該調(diào)用AssetDatabase.Refresh 將更改提交至數(shù)據(jù)庫,并使其顯示在工程中噪伊。
創(chuàng)建資源
創(chuàng)建文件的API是:CreateAsset
Material material = new Material (Shader.Find(“Specular”));
AssetDatabase.CreateAsset(material, “Assets/MyMaterial.mat”);
if(AssetDatabase.Contains(material)) //判斷是否包含這個資源
Debug.Log(“Material asset created”);
創(chuàng)建文件夾
創(chuàng)建文件夾:CreateFolder
ret = AssetDatabase.CreateFolder("Assets", "NewFolder");
if(AssetDatabase.GUIDToAssetPath(ret) != "")
Debug.Log("Folder asset created");
else
Debug.Log("Couldn‘t find the GUID for the path");
重命名
給文件夾重新命名:RenameAsset
ret = AssetDatabase.RenameAsset(“Assets/MyMaterial.mat”, “MyMaterialNew”);
if(ret == “”)
Debug.Log(“Material asset renamed to MyMaterialNew”);
else
Debug.Log(ret);
移動資源位置
移動資源所在的位置:MoveAsset
得到資源所在路徑:GetAssetPath
ret = AssetDatabase.MoveAsset(AssetDatabase.GetAssetPath(material), "Assets/NewFolder/MyMaterialNew.mat");
if(ret == "")
Debug.Log("Material asset moved to NewFolder/MyMaterialNew.mat");
else
Debug.Log(ret);
復(fù)制資源
復(fù)制一個資源:CopyAsset
if(AssetDatabase.CopyAsset(AssetDatabase.GetAssetPath(material), "Assets/MyMaterialNew.mat"))
Debug.Log("Material asset copied as Assets/MyMaterialNew.mat");
else
Debug.Log("Couldn‘t copy the material");
移動到回收站
把資源移動到回收站:MoveAssetToTrash
if(AssetDatabase.MoveAssetToTrash(AssetDatabase.GetAssetPath(MaterialCopy)))
Debug.Log("MaterialCopy asset moved to trash");
刪除資源
刪除一個資源或文件夾:DeleteAsset
if(AssetDatabase.DeleteAsset(AssetDatabase.GetAssetPath(material)))
Debug.Log("Material asset deleted");
if(AssetDatabase.DeleteAsset("Assets/NewFolder"))
Debug.Log("NewFolder deleted");
官方API網(wǎng)址:<font color=steelblue size=3>https://docs.unity3d.com/ScriptReference/AssetDatabase.html</font>