1.首先新建C#腳本,命名爲MenuItemTool
2.打開MenuItemTool腳本,編寫代碼如下:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class MenuItemTool : MonoBehaviour {
//靜態成員是和類一起存在的,有了類就有了靜態成員,我們可以通過類來訪問靜態成員(static)
//非靜態成員是和對象一起存在的,有了對象纔有非靜態成員,非靜態成員通過對象來訪問
[MenuItem("ClearMemory/ClearALL")]
static void ClearALL()
{
Debug.Log("清除所有緩存");
}
}
3.保存後返回unity界面發現多處一個菜單按鈕
點擊ClearAll後控制檯顯示如下:
同時可以擴展多個菜單按鈕:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class MenuItemTool : MonoBehaviour {
//靜態成員是和類一起存在的,有了類就有了靜態成員,我們可以通過類來訪問靜態成員(static)
//非靜態成員是和對象一起存在的,有了對象纔有非靜態成員,非靜態成員通過對象來訪問
[MenuItem("ClearMemory/ClearALL")]
static void ClearALL()
{
Debug.Log("清除所有緩存");
}
[MenuItem("ClearMemory/ClearOther")]
static void ClearOther()
{
Debug.Log("清除其它緩存");
}
}
unity中擴展的菜單如下;
4.添加二級菜單
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class MenuItemTool : MonoBehaviour {
//靜態成員是和類一起存在的,有了類就有了靜態成員,我們可以通過類來訪問靜態成員(static)
//非靜態成員是和對象一起存在的,有了對象纔有非靜態成員,非靜態成員通過對象來訪問
[MenuItem("ClearMemory/ClearALL",false,1)]
static void ClearALL()
{
Debug.Log("清除所有緩存");
}
[MenuItem("ClearMemory/ClearOther/ClearShopInfor",false, 2)]
//false代表是否可用,如果改爲true就會顯示不出來,False就可以在菜單中顯示出來
//第三個數字代表優先級
static void ClearShopInfor()
{
Debug.Log("清除商店緩存");
}
[MenuItem("ClearMemory/ClearOther/ClearPropInfor", false, 3)]
static void ClearPropInfor()
{
Debug.Log("清除裝備緩存");
}
}
其中false代表是否可用,如果改爲true就會顯示不出來,False就可以在菜單中顯示出來,第三個數字代表優先級,1代表優先級最高。
5.菜單同級的按鈕進行分組,優先級的數值要相差11
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class MenuItemTool : MonoBehaviour {
//靜態成員是和類一起存在的,有了類就有了靜態成員,我們可以通過類來訪問靜態成員(static)
//非靜態成員是和對象一起存在的,有了對象纔有非靜態成員,非靜態成員通過對象來訪問
[MenuItem("ClearMemory/ClearOther/ClearShopInfor",false, 12)]
//false代表是否可用,如果改爲true就會顯示不出來,False就可以在菜單中顯示出來
//第三個數字代表優先級
static void ClearShopInfor()
{
Debug.Log("清除商店緩存");
}
[MenuItem("ClearMemory/ClearOther/ClearPropInfor", false, 4)]
static void ClearPropInfor()
{
Debug.Log("清除裝備緩存");
}
[MenuItem("ClearMemory/ClearAll", false, 15)]
static void ClearAll()
{
Debug.Log("清除所有緩存");
}
[MenuItem("ClearMemory/ClearGameInfor", false, 26)]
static void ClearGameInfor()
{
Debug.Log("清除遊戲緩存");
}
//數字差值爲11的時候會自動分組
}
結果:
如果不分組的對比如下:
6.如果想在菜單欄中其他對象下面加按鈕
只需增加代碼:
[MenuItem("GameObject/Test")]
static void Test()
{
Debug.Log("測試");
}
沒有設置優先級時候默認加入到最後面
想把test加入到UI中可以加入優先級
[MenuItem("GameObject/UI/Test", false, 10)]
static void Test()
{
Debug.Log("測試");
}