Adding the little padlock button to your EditorWindow!

One of the less well known features of Unity is the little padlock button that lives in the upper-right corner of the Inspector window. This button is fantastic because it causes the inspector to ignore future selections and thus allowing you to select other objects without affecting the contents of the inspector.

Those who are needing (or just want the fancy little padlock!) to achieve a similar type of locking functionality in their own custom editor windows can simply by adding the magic method “ShowButton” to their editor window class. In fact, you don’t have to add a padlock, you could add some other icon!

Screenshot of custom editor window with lock icon.

Warning - This is non-documented functionality. Use at your own risk!

Since Unity 4.0 has become possible to add custom items to the editor window popup menu using the IHasCustomMenu interface.

Here is a simple example of how to achieve this:

using UnityEngine;
using UnityEditor;
 
public class WindowWithLockIcon : EditorWindow, IHasCustomMenu
{
    /// <summary>
    /// Menu item to display our test window.
    /// </summary>
    [MenuItem("Window/Window with Lock Icon")]
    private static void Show()
    {
        GetWindow<WindowWithLockIcon>("Lock Test");
    }
 

    /// <summary>
    /// Keep local copy of lock button style for efficiency.
    /// </summary>
    [System.NonSerialized]
    private GUIStyle lockButtonStyle;
    /// <summary>
    /// Indicates whether lock is toggled on/off.
    /// </summary>
    [System.NonSerialized]
    private bool locked = false;
 
    /// <summary>
    /// Magic method which Unity detects automatically.
    /// </summary>
    /// <param name="position">Position of button.</param>
    private void ShowButton(Rect position)
    {
        if (this.lockButtonStyle == null) {
            this.lockButtonStyle = "IN LockButton";
        }
        this.locked = GUI.Toggle(position, this.locked, GUIContent.none, this.lockButtonStyle);
    }
 
    /// <summary>
    /// Adds custom items to editor window context menu.
    /// </summary>
    /// <remarks>
    /// <para>This will only work for Unity 4.x+</para>
    /// </remarks>
    /// <param name="menu">Context menu.</param>
    void IHasCustomMenu.AddItemsToMenu(GenericMenu menu)
    {
        menu.AddItem(new GUIContent("Lock"), this.locked, () => {
            this.locked = !this.locked;
        });
    }
}