How to execute MenuItem for multiple objects once.

How can I write custom editor MenuItem command so it will be called for all selected objects.

Now it is called for every selected object, but I want to handle all selected objects in one command (through Selection.gameObjects i think) and suppress call for every selected object.

Use the parametered version of the method:

static public void MethodName(MenuCommand menuCommand)
{
            //Prevent executing multiple times when right-clicking.
		if (Selection.objects.Length > 1)
		{
			if (menuCommand.context != Selection.objects[0])
			{
				return;
			}
		}
}

Unfortunately the option above doesn’t work if you want to manage selection inside your custom menu method. Here is my workaround:

private static float _lastMenuCallTimestamp = 0f;
[UnityEditor.MenuItem("GameObject/Menu Option", priority = 0)]
private static void YourMenuOption() {
        if (Time.unscaledTime.Equals(_lastMenuCallTimestamp)) return;
        // place your code here
        _lastMenuCallTimestamp = Time.unscaledTime;
}

I’ve also tried using EditorApplication.timeSinceStartup and Time.timeSinceStartup but I couldn’t get a persistent timestamp with those. It seems like timeSinceStartup values are synchronized with the system time and keep updating even when Unity freezes (e.g. when you’re trying to apply your custom menu method to a large number of objects).

Another option is to simply deselect the menu items after the first call.

 private static void YourMenuOption() {
         if (Selection.objects.Length <= 0) return;
         // place your code here
         Selection.objects = null;
 }

as @LW said, MenuCommand.context could be null.

so try this code. Can work both right click and top bar menu.

[MenuItem("GameObject/YourMenuItem", false, 49)]
public static void YourMenuItem(MenuCommand menuCommand)
{
    if (ShouldExecute(menuCommand))
    {
        Debug.Log($"{menuCommand.context} {Selection.activeObject}");
        // ... do something
    }
}


private static bool ShouldExecute(MenuCommand menuCommand)
{
    if (menuCommand.context == null) return true;

    if (menuCommand.context == Selection.activeObject) return true;

    return false;
}

Not an answer but crazily enough, if you call the menu item from the top menu bar (Unity 2018.2.19f1) it only calls it once aannndddd the MenuCommand.context is null… which is probably a bug.