關鍵概念:
-
[InitializeOnLoadMethod] : 該修飾告訴 Unity ,被修飾的方法在腳本編譯完後首先調用。必須時靜態方法。
-
MenuItem(“Asset/XXX”) : 右鍵菜單。
-
[MenuItem(“Asset/Create/XXX”)] : 右鍵菜單,以及在窗口左上角的 Create菜單顯示。
-
EditorApplication.projectWindowItemOnGUI : Project 繪製委託。簽名:void OnGUI(string guid, Rect selectionRect)。
- string guid: 資源的 guid
- Rect selectionRect : 選中資源項的顯示區域。
-
EditorApplication.projectChanged : 監聽 Project 改變的委託。
-
string AssetDatabase.GetAssetPath(Object) : 獲取資源的路徑。
-
string AssetDatabase.AssetPathToGUID(string) : 將資源路徑轉換成 GUID。
-
bool GUI.Button(Rect rect, string name) : 在指定區域繪製按鈕,返回用戶是否點擊。
-
GUI.colro : 指定 UI 繪製的顏色。
例子:
using UnityEditor;
using UnityEngine;
/// <summary>
/// 擴展 Project 窗口
/// 通過派生 UnityEditor.AssetModificationProcessor 監聽資源狀態時間
/// </summary>
public class ProjectWindowExtend : UnityEditor.AssetModificationProcessor
{
// 右鍵菜單
[MenuItem("Assets/My Tools/Tools", false, 1)]
static void OnMyTool()
{
Debug.Log("Run my tool.");
}
// 右鍵菜單以及左上角的Create菜單
[MenuItem("Assets/Create/My Create/Sphere", false, 1)]
static void OnMyCreateSphere()
{
GameObject.CreatePrimitive(PrimitiveType.Sphere);
}
[InitializeOnLoadMethod] // 腳本編譯完成後首先調用
static void InitializeOnLoadMethod()
{
// 繪製方法
EditorApplication.projectWindowItemOnGUI += delegate (string guid, Rect selectionRect)
{
if (guid.Length > 0 && Selection.activeObject)
{
string path = AssetDatabase.GetAssetPath(Selection.activeObject);
string assetGUID = AssetDatabase.AssetPathToGUID(path);
if (guid == assetGUID)
{
float width = 50.0f;
selectionRect.x += selectionRect.width - width;
selectionRect.y += 2;
selectionRect.width = width;
GUI.color = Color.red;
//點擊事件
if (GUI.Button(selectionRect, "click"))
{
Debug.Log($"click: {Selection.activeObject.name}");
}
GUI.color = Color.white;
}
}
};
// 監聽任意所有的變化
EditorApplication.projectChanged += delegate ()
{
Debug.Log("changed");
};
}
// 監聽雙擊左鍵,打開資源事件,會調用很多次?
public static bool IsOpenForEdit(string assetPath, out string message)
{
message = null;
Debug.Log($"Open for eidt asset:{assetPath}");
// 返回true表示允許打開資源,false表示不可以再unity中打開該資源
return true;
}
// 監聽資源將要被創建事件
public static void OnWillCreateAsset(string path)
{
Debug.Log($"Will create asset:{path}");
}
// 監聽資源將要被保存
public static string[] OnWillSaveAsset(string[] paths)
{
for (int i = 0; i < paths.Length; ++i)
{
Debug.Log($"Will save assets:{paths[i]}");
}
return paths;
}
// 監聽資源將要被移動事件
public static AssetMoveResult OnWillMoveAsset(string oldPath, string newPath)
{
Debug.Log($"Will move asset form:{oldPath} to:{newPath}");
// 告訴內部實現,該腳本已經進行了移動,內部實現將不再移動資源
return AssetMoveResult.DidMove;
}
// 監聽資源將要被刪除事件
public static AssetDeleteResult OnWillDeleteAsset(string assetPath, RemoveAssetOptions option)
{
Debug.Log($"Will delete asset:{assetPath}. option:{option}");
// 告訴內部實現,該腳本沒有刪除資源,需要內部刪除
return AssetDeleteResult.DidNotDelete;
}
}