A Summary of Unity Attributes

The post was updated with attributes from Unity 5.3 RC1.

Unity usesattributes attributes all over the place for declaring different things to the engine.

The latest release (5.3) has a whopping count of 77 (!) attributes to decorate your classes, methods and fields. New attributes added in latest versions are highlighted throughout this post.

This post is a only a summary of all of Unity’s (public) attributes (i skipped over a few related to Boo, or attributes for UNet which deserve a dedicated post of their own). I believe that by this way of exploring APIs, we can learn more and expand our knowledge of what’s available in the engine; I certainly found a few attributes that were useful for my day-to-day job this way !

While this post is only a summary, I’ll attempt to link each attribute to a follow-up post where i demonstrate how, and more importantly – when you should use it.

NOTE: some of these attributes are undocumented and some are probably ‘leftovers’ from older versions that are not used any more.

Leave a comment with how many attributes you actually knew and used 🙂

How Attributes Were Counted

The following code snippet was used to query for all attributes. It takes into consideration public attributes from all assemblies loaded into the current app domain, omitting attributes that are marked as Obsolete:

using System.Linq;
using UnityEngine;
using UnityEditor;
using System;

public class AttributesCounter 
{
    [MenuItem("Tools/Print all attributes")]
    private static void Start ()
    {
        // Get loaded assemblies with "Unity" in their name
        var assemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => a.FullName.Contains("Unity"));

        foreach (var a in assemblies)
        {
            var attributes = a.GetExportedTypes ().Where (IncludeType).OrderBy(t => t.FullName).ToArray();

            foreach (var attrib in attributes)
            {
                Debug.LogFormat("[Attribute] {0} - {1}", a.GetName().Name, attrib.FullName);
            }
        }
    }

    private static bool IncludeType(Type t)
    {
        return t.IsPublic
            && !t.IsDefined(typeof(ObsoleteAttribute), true)
            && typeof(Attribute).IsAssignableFrom(t);
    }
}

UnityEngine

These attributes are defined in UnityEngine.dll and are available to both editor and runtime classes:

(Unity 5) Editor Related

  • UnityAPICompatibilityVersionAttribute – Placed at the assembly level, and signals to Unity that the assembly is compatible with a given API version (this will avoid the attempt to “upgrade” the code in the assembly to Unity 5 level).
  • (NEW) ColorUsageAttribute – placed on Color fields to determine how the color picker will behave for it.

Inspector Related

  • (NEW) HelpURLAttribute – provides a custom URL for documentation.
  • PropertyAttribute – A base class to derive custom property attributes from. These attributes are used over script public variables to control how they are drawn in the inspector. For more info see link, link
  • TooltipAttribute – A built-in PropertyAttribute that adds a tooltip to script variables in the inspector.
  • SpaceAttribute – A built-in PropertyAttribute that adds spacing around script variables in the inspector.
  • HeaderAttribute – A built-in PropetyAttribute that adds a header over a script variable in the inspector.
  • RangeAttribute – A built-in PropertyAttribute that constrains an int/float field in the inspector to a specified range.
  • MultilineAttribute – A built-in PropertyAttribute that changes string editing in the inspector to a multi-line textbox.
  • TextAreaAttribute – A built-in PropertyAttribute that allows string editing in the inspector inside a flexible text area.
  • HideInInspector – Hides a field from being displayed in the inspector (although it is still serialized).
  • SerializeField – Notifies Unity that the field decorated by the attribute should be serialized.
  • FormerlySerializedAsAttribute – Provides a way to rename fields after they’ve been assigned without losing their values.

Menu Related

  • AddComponentMenu – Allows placing custom scripts (MonoBehaviours) under a different category of the Add Component menu (the default is under Scripts).
  • ContextMenu – Add custom commands to the inspector’s context menu of the current script.
  • ContextMenuItemAttribute – Used to add a context menu (right-click menu) in the inspector for a specific field. See this link for more information.
  • (NEW) CreateAssetMenuAttribute – Marks a ScriptableObject derived class so it will be listed under Assets/Create (this helps in the creation of ScriptableObject instances, instead of having to write your own custom code for instantiating them).

Runtime

  • (Unity 5) RuntimeInitializeOnLoadMethodAttribute – Same as the editor counterpart, allows automatically executing a method (when the game runtime loads).
  • (Unity 5) SharedBetweenAnimatorsAttribute – Marks a StateMachineBehaviour to be instantiated only once, since it should be shared between animators.
  • RPC – Marks a method so that it can be used along with Unity networking and be invoked by remote clients.
  • ExecuteInEditMode – Placed over a script (MonoBehaviour) to have it execute even when not in play mode.
  • (NEW) PreserveAttribute – prevents a class, method or field from being stripped, in case stripping is enabled

Components Related

  • DisallowMultipleComponent – Prevents the same component from being added twice to the same game object.
  • RequireComponent – Specifies that a component marked by this attribute requires another component (which will automatically be added when using the component).
  • MonoPInvokeCallbackAttribute – Allows registering a static method so it can be passed and invoked from unmanaged code. See this link for more info.
  • ThreadSafeAttribute – No documentation 🙁 *may* be related to this
  • ConstructorSafeAttribute – No documentation 🙁 Probably used by native code/Mono.
  • AssemblyIsEditorAssembly – Marks all types in an assembly to be considered as editor classes.
  • SelectionBaseAttribute – Marks scripts as selection bases (defines the behaviour of which object will be picked when selected in the scene view).
  • DefaultValueAttribute – Compiler-injected attribute when using default values for method parameters.
  • ExcludeFromDocsAttribute – Probably used internally to hide certain classes from the auto-generated documentation.
  • TypeInferenceRuleAttribute – No documentation 🙁
  • ImageEffectTransformsToLDR – Switch to LDR rendering
  • ImageEffectOpaque – Image effects marked with this attribute will be rendered after opaque geometry (but before transparent geometry).

Unknown (Flash Related?)

  • ImplementedInActionScriptAttribute – No documentation 🙁 Probably not used anymore.
  • NotConvertedAttribute – Instructs the build pipeline to not convert the given type to the target platform.
  • NotFlashValidatedAttribute – Don’t try to validate a type/member for the Flash platform.
  • NotRenamedAttribute – Prevents name mangling of constructors, methods, field names.

(Unity 5) Jetbrains.Annotations

Unity 5 embeds a set of JetBrains.Annotations directly inside UnityEngine.dll (for more info as to why – see this link). As described in their documentation, these work in synergy with ReSharper’s analysis engine (we’ll not elaborate on these):

  • AssertionMethodAttribute
  • BaseTypeRequiredAttribute
  • CanBeNullAttribute
  • CannotApplyEqualityOperatorAttribute
  • ContractAnnotationAttribute
  • InstantHandleAttribute
  • InvokerParameterNameAttribute
  • LinqTunnelAttribute
  • LocalizationRequiredAttribute
  • MeansImplicitUseAttribute
  • NoEnumerationAttribute
  • NotifyPropertyChangedInvocatorAttribute
  • NotNullAttribute
  • neferenceAttribute
  • PublicAPIAttribute
  • PureAttribute
  • StringFormatMethodAttribute
  • UsedImplicitlyAttribute

UnityEditor

These attributes that are defined in the UnityEditor.dll and are available to editor classes:

  • (NEW) DrawGizmoAttribute – allows supplying a custom gizmo renderer for any given component type
  • InitializeOnLoadAttribute – Allows running custom code when the editor launches.
  • (Unity 5) InitializeOnLoadMethodAttribute – Same as the above, but can be used on a method.
  • CustomPreviewAttribute – Mark a class as the provider of a custom preview for a given type.
  • CustomPropertyDrawer – Provides information for property drawers (or decorator drawers) on which type they’re a drawer for. See this link.
  • TreeAttribute – No Documentation 🙁 Seems related to Unity’s tree editor.
  • CallbackOrderAttribute – Defines callback order ???
  • PostProcessBuildAttribute – Used to mark a method that will be called following a build (to allow post processing of the final output).
  • PostProcessSceneAttribute – Get a notification just before building a scene (allows to perform processing before it is built).
  • DidReloadScripts – mark a method with this attribute to receive a notification when scripts were reloaded.
  • OnOpenAssetAttribute – Marks a method to be called when opening (double-clicking) an asset in the project browser.
  • CustomEditor – Provides an Editor derived class (inspector) the type it is editing.
  • CanEditMultipleObjects – Marks a custom editor (inspector) as able to edit multiple objects at the same time.
  • PreferenceItem – Adds custom preferences section to the preferences window.
  • MenuItem – Adds a menu item to the main editor window and inspector windows.
This entry was posted in Unity and tagged , , , . Bookmark the permalink.
  • pharan

    These two attributes were added recently. They’re really nice. I thought they’d be worth updating the article for since you updated it for 5.0.

    [ColorUsage]
    You put it on Color fields and based on the arguments, you can enable or disable the alpha in the color picker, or allow HDR colors (under the hood, a Color that can have channel values more than 1f. Useful for certain shaders or color operations but doesn’t work for the Sprite type.) Unfortunately, it also doesn’t work for Gradient fields.
    http://docs.unity3d.com/ScriptReference/ColorUsageAttribute.html

    [CreateAssetMenu]
    You put it on ScriptableObjects and it allows you to add the type as an item in the Create menu. Clicking it creates a new asset with the ScriptableObject in it. No need for custom editor classes to create ScriptableObject assets now.
    http://docs.unity3d.com/ScriptReference/CreateAssetMenuAttribute.html

    • Lior Tal

      Thanks for the comment; i will update this post with all attributes in the latest 5.2 release.

      • Lior Tal

        Hey, the post was updated with all new stuff in 5.2 🙂

        I actually think it would be a good idea to create follow up posts to show how to use these in an actual game.. what do you think ? (some of these don’t have proper documentation or examples).

        • pharan

          You mean individual posts for specific attributes? Sounds cool, especially for the less documented ones, and ones that could stand a bit more explaining because they’re interesting and useful or have some gotchas.

          For example, I liked the idea behind [DrawGizmoAttribute] (and being able to move my gizmo code into CustomEditors and out of my MonoBehaviours. But I noticed that using that attribute achieves the same gizmo drawing visually but actually causes the gizmos to not be selectable— which is a feature you get if you define an OnDrawGizmos method instead. (I’ve also found that its GizmoType parameter behaves in ways I still don’t get.)

          I just gave the updated article a quick read through and I found [OnOpenAssetAttribute]. That’s a pretty cool callback that I didn’t know about. Just added it to my project. Works like a charm.

          I’m on that MonoDevelop 5.9 thread if you need to pm me on the forums.

          • Lior Tal

            One post per attribute is too much, but as you see i tried to group them by different categories so i could do one post per category

  • Altaf

    Thank you so much for Sharing this. Really useful

  • Pretty sure TypeInferenceRuleAttribute is related to duck-typing, used to mark the official API so that UnityScript knows how to automagic. Nothing interesting from a user standpoint IMO.

  • Pingback: 7 Ways to Make Your Unity Components More User-Friendly()

  • Pingback: Issue 7 – Unity Dev Weekly()