Unity3D自定義菜單組件


1.在Component菜單欄中添加新的菜單項
[AddComponentMenu("Transform/AddComponentTest", 10)]
public class AttributeTest : MonoBehaviour{}
點擊AddComponentTest則可以向目標GameObject添加AttributeTest腳本
2.添加新的菜單欄以及菜單項
[MenuItem("MyMenu/Do Something")]//MenuItem特性會將所有的靜態方法變為菜單命令
static void DoSomething() {
}

//定義一個輸出Transform名稱的選項,首先要判斷選中的是不是Transform對象,不是則不激活該選項
[MenuItem ("MyMenu/Log Selected Transform Name")]
static void LogSelectedTransformName() {
    Debug.Log(Selection.activeTransform.gameObject.name);
}

//判斷是否激活菜單項,返回true則激活
[MenuItem ("MyMenu/Log Selected Transform Name", true)]
static bool IsActiveMenu() {
    return Selection.activeTransform != null;
}

//創建菜單項並添加快捷鍵Ctrl + G
[MenuItem ("MyMenu/Do Something With A Shortcut Key %g")]
static void DoSomethingWithAShortcutKey() {
    Debug.Log("Do Something With A Shortcut Key...");
}

3.在Component組件的Context中添加新的菜單項
//在Unity中Rigidbody的context增加一個Double Mass菜單項
[MenuItem ("CONTEXT/Rigidbody/Double Mass")]
static void DoubleMass(MenuCommand command) {
    Rigidbody body = (Rigidbody)command.context;
    body.mass = body.mass * 2;
    Debug.Log("Change Mass Double!");
}

4.創建一個新的自定義GameObject
//三個參數分別控制菜單項的名稱,是否激活,顯示層級
[MenuItem("GameObject/MyCaregory/Custom Game Object", false, 10)]
static void CreateCustomGameObject(MenuCommand command) {
    GameObject go = new GameObject("Custom Game Object");
    GameObjectUtility.SetParentAndAlign(go, command.context as GameObject);
    Undo.RegisterCreatedObjectUndo(go, "Create " + go.name);
    Selection.activeObject = go;
}

5.定義自己的定制特性類
//第一個參數用來給定該特性的適用范圍
[AttributeUsage(AttributeTargets.Class, Inherited = false)]
public class CustomAttribute : System.Attribute{   }

[CustomAttribute]
public class CustomAttributeTest : MonoBehaviour
{
    void Start()
    {
        //打印為True
        Debug.Log(this.GetType().IsDefined(typeof(CustomAttribute), false));
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM