2
\$\begingroup\$
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;
using System.IO;
using System.Text.RegularExpressions;

public class Test : Editor
{
    [MenuItem("Assets/Testing")]
    private static void Init()
    {

    }
}

When I right click on the Assets I will see the "Testing" item defined above in the context menu.

But I want to see this "Testing" option only if I right click on a script file (.cs or .js)

For example if I have a script file at Assets > Test > Test.cs, only when I right mouse click on Test.cs should the context menu show the new Testing option.

How can I do this?

\$\endgroup\$
2
\$\begingroup\$

Short answer - you can`t "hide context menu options".

But you can disable certain menuitems with "Validation" methods. This system adds new validation method to already existing context menu, this method must return bool, true == enabled, false == disabled. Also in MenuItem attribute you must pass true as second parameter to mark that method as validator, MenuItem path must be the same as original method.

For your example with scripts you must compare current selection object with MonoScript type which represents C# scripts in Unity.

[MenuItem("Assets/Do Something")]
private static void DoSomething() {
    Debug.Log("You did something!");
}

[MenuItem("Assets/Do Something", true)]
private static bool DoSomethingValidation() {
    return Selection.activeObject.GetType() == typeof(MonoScript);
}

Example of disabled Menu Item

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ In most of the times when doing right click mouse on the Assets make the Do Something enabled same when doing it on a script file. After some times clicking on the Do Something then it disable it in the Assets but then when doing it in the file again it enable it again also on the Assets. It's not allways disabled on the Assets when doing right click. \$\endgroup\$ – BenBen Shmil Aug 11 '18 at 18:24
  • \$\begingroup\$ I'm not sure I did fully understand you. I've tested these 2 methods on several folders and different assets and scripts - everything works fine on my side. Can you provide some addition info, with screenshots maybe? \$\endgroup\$ – user109982 Aug 11 '18 at 18:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.