Click set in the component (right-click) to bring up the context menu. We can expand the new menu bar in the original menu. The Code is as follows:
Using unityengine; using unityeditor; public class context menu {[menuitem ("context/transform/new context 1")] public static void newcontext1 (menucommand command) {// obtain the object name debug. log (command. context. name);} [menuitem ("context/transform/new context 2")] public static void newcontext2 (menucommand command) {debug. log (command. context. name );}}
[Menuitem ("context/transform/new context 1")] indicates that the new menu is extended on the transform component. If you want to expand on another component, such as the camera component, directly modify the transform in the string to camera. If you want to add a menu bar to all components, change it to compoment. The code works as follows:
In addition, the preceding settings can also be applied to scripts written by the user. The Code is as follows:
Using unityengine; # If unity_editorusing unityeditor; # endifpublic class context menu 2: monobehaviour {Public String contextname; # If unity_editor [menuitem ("context/Context Menu 2/new context 1")] public static void newcontext2 (menucommand command) {context menu 2 script = (command. context as context menu 2); script. contextname = "Hello world! ";}# Endif}
This Code uses menucommand to obtain the script object and access the variables in the script. The macro definition label is also used. The unity_editor code is executed only in editor mode, and the code will be removed after it is published. The effect is as follows:
Of course, we can also write this in our own scripts. If it is the same as the menu name in the system, it can be overwritten. For example, here we overwrite the button for deleting a component so that we can perform some of our operations:
[Contextmenu ("Remove comconent")] void removecomponent () {debug. log ("removecomponent"); // delete your unityeditor after one frame. editorapplication. delaycall = delegate () {destroyimmediate (this );};}
In edit mode, Code Synchronization may fail. For example, if destroyimmediate (this) deletes its own code, an error at the bottom of the engine is triggered. However, we can use unityeditor. editorapplication. delaycall to delay a single call. If you find similar problems when developing editor code, you can try to delay one frame before executing your code.
Extended Editor (12) _ context menu