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.
Screenshot of custom editor window with lock icon.

Warning: This is non-documented functionality which is not supported by the developers of Unity. 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")]
    static void Show() {
        GetWindow<WindowWithLockIcon>("Lock Test");
    }

    /// <summary>
    /// Keep local copy of lock button style for efficiency.
    /// </summary>
    [System.NonSerialized]
    GUIStyle lockButtonStyle;
    /// <summary>
    /// Indicates whether lock is toggled on/off.
    /// </summary>
    [System.NonSerialized]
    bool locked = false;

    /// <summary>
    /// Magic method which Unity detects automatically.
    /// </summary>
    /// <param name="position">Position of button.</param>
    void ShowButton(Rect position) {
        if (lockButtonStyle == null)
            lockButtonStyle = "IN LockButton";
        locked = GUI.Toggle(position, locked, GUIContent.none, 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"), locked, () => {
            locked = !locked;
        });
    }

}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s