C# Create new editor menu from array

Hello,

Is it possible to create an editor menu from an array? I’m getting all the prefabs in a folder from an editor script and was wondering how to dynamically create editor menus from the array of prefabs to load them from.

I don’t understand what you’re trying to do. Perhaps you can explain a bit more.

Do I understand you want to give a restricted choice to the user of your editor?

It is not exactly clear what you are asking for, but one option might be to just provide a single menu with all the commands and then add validators to disable the ones which are not appropriate for the current context:

using UnityEngine;
using UnityEditor;

static class YourMenuItems {
    [MenuItem("Your Menu/Foo")]
    private static void Foo() {
        Debug.Log(Selection.activeTransform.name);
    }
    [MenuItem("Your Menu/Foo", true)]
    private static bool ValidateFoo() {
        // Menu item is only useful when there is a user selection.
        return Selection.activeTransform != null;
    }
}

Or, perhaps you are wanting to add a custom dynamic menu within your own editor window/inspector?

using UnityEngine;
using UnityEditor;

public class YourEditorWindow : EditorWindow {
    private void OnGUI() {
        if (GUILayout.Button("My Menu"))
            ShowMyMenu(GUILayoutUtility.GetLastRect());
    }

    private void ShowMyMenu(Rect position) {
        var menu = new GenericMenu();

        menu.AddItem(new GUIContent("Always Available A", false, () => {
            Debug.Log("Clicked 'Always Available A' menu item!");
        }));

        menu.AddSeparator("");

        menu.AddItem(new GUIContent("Always Available B", false, () => {
            Debug.Log("Clicked 'Always Available B' menu item!");
        }));

        if (Selection.activeTransform != null) {
            // Only show this menu when an object is selected!
            menu.AddItem(new GUIContent("Name of Selected Transform", false, () => {
                Debug.Log(Selection.activeTransform.name);
            }));
        }

        menu.DropDown(position);
    }
}

I hope that this helps :slight_smile:

2 Likes

I apologize, I forgot about this thread. Here’s what I wanted to do.

I have traffic car Prefabs in a folder in the Assets folder of the project. I want the user to be able to add vehicle prefabs, and then have them come up in the menu option. So, adding a menu option per prefab in the folder, dynamically.

What numberkruncher posted should give you just that.

GenericMenu menu = new GenericMenu();
foreach(GameObject prefab in AssetDatabase.LoadAllAssetsAtPath(PATH))
{
    menu.AddItem(new GUIContent(prefab.name), false, SelectPrefab, prefab);
}

Or something similar…

If you have a lot of object, you can maybe look into the link in my signature. It’s a modal window for listing choices to the user in editor mode.

1 Like