Prevent 'Paste Component Values' on MonoBehaviour

I have a custom MonoBehaviour class and would like to remove or disable the menu items for copying and pasting since they do not make sense for this particular behaviour. If used, these menu items will lead to trouble!

  • Copy Component
  • Paste Component as New
  • Paste Component Values

Is there a way to achieve this?

Hello there again :slight_smile:

So I’ve been fiddling around trying to find a public way to modify this behavior, I couldn’t find any. Via reflection, I found out that the method responsible for drawing the Help and Settings context menu, is DrawHeaderHelpAndSettingsGUI in UnityEditor.Editor - If you go to UnityEditor.Editor.DrawHeaderGUI you’ll see a call to it there (this is all part of the inspector window OnGUI - It’s in UnityEditor.InspectorWindow if you wanna check it out feel free)

If we take a peek inside DrawHeaderHelpAndSettingsGUI we’ll see a call to DisplayObjectContextMenu, which in turns calls the internal method Internal_DisplayObjectContextMenu - This is really what we care about.

Using the same injecting techniques in here and here, we can definitely do something about it! - Here’s what I did:

1- Created a wrapper for Internal_DisplayObjectContextMenu that won’t display context options for certain types:

public static List<Type> typesToExcludeFromContextMenu = new List<Type>
{
	typeof(AwesomeColTest)	//, etc
};

public static void Internal_DisplayObjectContextMenu(Rect position, Object[] context, int contextUserData)
{
	if (context.Any(c => typesToExcludeFromContextMenu.Contains(c.GetType())))
		return;

	typeof(EditorUtility)
		.GetMethod(
			"Internal_DisplayObjectContextMenu",
			BindingFlags.Static | BindingFlags.NonPublic,
			null,
			new Type[] { typeof(Rect), typeof(Object[]), typeof(int) },
			null)
		.Invoke(null, new object[] { position, context, contextUserData });
}

2- redirected the method call to Internal_DisplayObjectContextMenu in DisplayObjectContextMenu to my wrapper:

3- Copy your patched dll to your Editor/Data/Managed folder

4- And that’s pretty much it :slight_smile:

DISCLAIMER: Do this shit on you own responsibility, I’m not responsible for the laws/stuff/etc that might be broken due to this hack. I do this for pure educational reasons.