- Home /
Can I make the name of a custom Menu Item context-sensitive, or show/hide it dynamically?
Can I change singular to plural, make the word "On" turn to "Off" when appropriate, etc., for a single function?
Alternatively, dynamically including and removing menu items as various states change, would be fine. Can that be done?
Complex, and in my unworthy opinion, unnecessary, but surely possible.
I don't believe you can. Since attributes require constant variables as parameters, your variable (probably a string) would have to be decided at compile-time, not runtime, and you couldn't change it.
I think you can't change the itemName of the attribute class because it seems the name is stored inside in a private variable. But you should be able to use Reflection to remove the attribute from that function and add a new one. $$anonymous$$aybe you can derive your own attribut class from $$anonymous$$enuItem, but i still think the name stored in a private var and not a protected one.
Furthermore I doubt that Unity will recognise the changes because i believe Unity itself use Reflection to check for those attributes at compilation time and will build the menu with this information. But would be nice to know ;)
You could implement your own editor window with a separately managed set of menus.
Answer by jashan · Jan 28, 2011 at 08:50 AM
As you define the name of menu items via an attribute (MenuItem), I don't see a way of changing the name of the menu dynamically. However, what you can do is have two entries and enabling/disabling them depending on context. This may not really make sense with singular / plural but it certainly makes sense for the on/off case (which is also what I'm actually using this for).
Simply use the second constructor of menu item from the documentation (this is C#, JavaScript can be found in the docs ;-) ):
// Validate the menu item.
// The item will be disabled if no transform is selected.
[MenuItem("GameObject/Do Something", true)]
static void ValidateDoSomething () {
return Selection.activeTransform != null;
}
So, you need two methods: One that actually defines the functionality of your menu item (that will just use MenuItem("Name")), and another one that checks for the context (that one will use MenuItem("Name", true") and return true when the menu item should be enabled and false if it should be disabled.
Oh, I use validation functions on pretty much all of my menu items. But although graying out and taking away the ability to click on or use a keyboard shortcut is nice, the words still remain. What I want is something more dynamic. For example, open any of Apple's apps, click on the "Window" menu, and tap the Option key. $$anonymous$$aybe the idea is that two different functions are called; I don't know. That would be just fine too and I'll edit the question to reflect that.
Your void is returning a bool... That wouldn't compile :P