0
votes

Task:

I want to create a context menu item that will work on GameObject selected in Hierarchy. This action should be available only when selected GameObject is a Prefab. I'm working on Unity 5.3.2

enter image description here

Code:

File MenuItems.cs is located in Assets\Editor

using UnityEditor;
using UnityEngine;

public static class MenuItems
{

    [MenuItem("GameObject/Action on prefab", false, 14)]
    private static void MenuActionPrefab()
    {
    }

    [MenuItem("GameObject/Action on prefab", true, 14)]
    private static bool ValidateMenuActionPrefab()
    {
        var isPrefab = PrefabUtility.GetPrefabParent(Selection.activeGameObject) != null;
        return isPrefab;
    }
}

Problem:

The problem is that the menu item is visible (and can be clicked) no matter if selected GameObject is a Prefab or not. I have tested code in debugger and value returned from ValidateMenuActionPrefab() is OK (true when I run it on Prefab, false on non-prefab gameobject).

I've read somewhere that Unity 5 have problem with validation methods but the example from UNITY EDITOR EXTENSIONS – MENU ITEMS about validation in Assets work perfectly OK.

Question:

So if this is a proper solution? Or is there another way to achieve same goal?

Additional info:

I have tried to run those methods simple way using:

[MenuItem("GameObject/Action on prefab")]

and

[MenuItem("GameObject/Action on prefab", true)]

but in this case there is no Action on prefab in context menu. Also this item isn't visible when I try not to set priority index.

Edit:

Behaviour should be simillar to Select Prefab item (visible on screenshot). When object isn't connected to prefab field should be grey and not-clickable. When object is a prefab field is black and can be clicked.

1

1 Answers

1
votes

I've just set up a new unity3d project and your code works then clicking on the menu Gameobject/Action on Asset.

I'm using Unity3d 5.3.4f1. Maybe it's a bug in your specific version, however I didn't find any mention about this neither in the 5.3.3 nor the 5.3.4 changelog

However when you right-click and open the context menu over an object in the hierarchy, the ValidationMethod is not called, so the context menu element is always enabled. But if you actually click the context menu item, then the validation method is called; if it returns false then no action is performed.

Seems like a bug, but at least is safe to use it.

Prefab selected

enter image description here

Instance selected

enter image description here