Ryan Nielson

The personal site and blog of Ryan Nielson.

© 2014. Ryan Nielson All rights reserved.

Controlling Object Visibility and Editability in Unity Using HideFlags

Unity game objects and components have an interesting feature called HideFlags. This allows you to control whether a game object or component is visible, editable, persistent, or any combination thereof.

Both GameObject and MonoBehaviour inherit from the Object class which contains the hideFlags property. This property can be set to any of the valid values in the HideFlags enumeration. By default it is set to HideFlags.None. Below are some examples and explanations of various options.

To run these examples, I've created a script that allows you to choose a HideFlags value and whether to set it on the game object or component. It sets the hideFlags property in OnEnable, so it will run when the game starts, or you can use it in combination with ExecuteInEditMode to run it while in the editor.

using UnityEngine;

public class HideFlagsSetter : MonoBehaviour
{
    public HideFlags customHideFlags;

    public enum Mode
    {
        GameObject,
        Component
    }

    public Mode setOn = Mode.GameObject;

    private void OnEnable()
    {
        if (setOn == Mode.GameObject)
        {
            gameObject.hideFlags = customHideFlags;
        }
        else if (setOn == Mode.Component)
        {
            hideFlags = customHideFlags;
        }
    }
}

HideFlags.HideInHierarchy

This option hides your game object in the hierarchy view, and makes it not selectable in the scene view. This has no effect if set on a component.

HideFlags.HideInHierarchy

HideFlags.HideInInspector

If set on a game object, this option hides all the components in the inspector.

HideFlags.HideInInspector

If set on a component, this option only hides the component in the inspector.

HideFlags.HideInInspector

HideFlags.NotEditable

If set on a game object, no components will be editable. The object will also not be selectable in the scene.

HideFlags.NotEditable

If set on a component, only that component will not be editable.

HideFlags.NotEditable

Other options include HideFlags.DontSaveInEditor, HideFlags.DontUnloadUnusedAsset, HideFlags.DontSaveInBuild, HideFlags.DontSave, and HideFlags.HideAndDontSave that mainly relate to scene and build persistence that I won't go into detail about here. More information about these can be found in the HideFlags Documentation.

You can download the example project to experiment with HideFlags using the script and example scene used in this post.

HideFlags can be a very useful tool in preventing the hierarchy from being cluttered and ensuring specific components are not editable. They're quite useful when working on assets in which the component values or game object structure are imporant. If you have any further questions please feel free to message me on Twitter @RyanNielson or comment below.

comments powered by Disqus