html所有attribute_Unity的内置Attribute一览

Attribute简介

Unity使用cs作为开发语言,而cs有一项非常重要的特性就是attribute。

attribute可以将元数据或声明性信息与代码(程序集,类型,方法,属性等)相关联。将attribute与程序实体相关联后,可以使用反射技术在运行时查询该属性。

Unity提供了大量内置的attribute方便我们的开发,本文就来介绍一下Unity的内置attribute。

想要知道Unity为我们提供了哪些attribute可以通过访问脚本引用文档查询:https://docs.unity3d.com/ScriptReference/index.html

9d33e905f0fb920af4084624adc45544.png

编辑器功能类

  • AddComponentMenu 为自己的组件更好的组织“添加组件菜单”。

using UnityEngine;[AddComponentMenu("Transform/Follow Transform")]public class FollowTransform : MonoBehaviour{}
  • ContextMenu 将组件的函数功能添加到组件的上下文菜单中,该函数需要是非静态的。

using UnityEngine;public class ContextTesting : MonoBehaviour{    /// Add a context menu named "Do Something" in the inspector    /// of the attached script.    [ContextMenu("Do Something")]    void DoSomething()    {        Debug.Log("Perform operation");    }}
  • ContextMenuItemAttribute 使用此属性可将上下文菜单添加到调用命名方法的字段中。

using UnityEngine;public class Example : MonoBehaviour{    [ContextMenuItem("Reset", "ResetBiography")]    [Multiline(8)]    string playerBiography = "";    void ResetBiography()    {        playerBiography = "";    }}
  • CreateAssetMenuAttribute 将一个ScriptableObject派生类型标记为自动在Assets / Create子菜单中列出,以便可以轻松创建该类型的实例并将其存储为“ .asset”文件。

  • CustomGridBrushAttribute 将该类定义为网格笔刷并使之在调色板窗口中可用的属性。

  • DisallowMultiComponent 防止将相同类型(或子类型)的MonoBehaviour多次添加到GameObject中。

  • ExcludeFromObjectFactory 将此属性添加到类中,以防止使用ObjectFactory方法创建该类及其继承的类。

  • ExcludeFromPresetAttribute 将此属性添加到类,以防止从类的实例创建预设。

  • ExcuteAlways 使脚本实例始终执行,无论是在“播放模式”中还是在编辑时。

  • ExcuteInEditorMode 使脚本的所有实例在“编辑模式”下执行。由于没有考虑Prefab模式,正在逐步淘汰,不建议使用。

  • GUITargetAttribute 用于控制OnGUI在哪个Display中被调用。Unity支持多相机输出给不同的Display。

  • HelpURLAttribute 提供一个类的自定义文档URL。

using UnityEngine;using UnityEditor;[HelpURL("http://example.com/docs/MyComponent.html")]public class MyComponent{}
  • PreferBinarySerialization 无论项目的资产序列化模式如何,都首选ScriptableObject派生类型以使用二进制序列化。该属性只能应用于ScriptableObject派生类,所有其他类型都将忽略该属性。

using UnityEngine;[CreateAssetMenu][PreferBinarySerialization]public class CustomData : ScriptableObject{    public float[] lotsOfFloatData = new[] { 1f, 2f, 3f };    public byte[] lotsOfByteData = new byte[] { 4, 5, 6 };}
  • RequireComponent 自动将所需的组件添加为依赖项。当您将使用RequireComponent的脚本添加到GameObject时,所需的组件将自动添加到GameObject。

using UnityEngine;// PlayerScript requires the GameObject to have a Rigidbody component[RequireComponent(typeof(Rigidbody))]public class PlayerScript : MonoBehaviour{    Rigidbody rb;    void Start()    {        rb = GetComponent();    }    void FixedUpdate()    {        rb.AddForce(Vector3.up);    }}
  • SelectionBaseAttribute 将此属性添加到脚本类,以将其GameObject标记为SceneView拾取的选择基础对象。

  • SerializeField 强制Unity序列化一个私有字段。Unity序列化脚本时,只会序列化公共字段。如果您还希望Unity序列化您的私有字段,则可以将SerializeField属性添加到这些字段。

using UnityEngine;public class SomePerson : MonoBehaviour{    //This field gets serialized because it is public.    public string firstName = "John";    //This field does not get serialized because it is private.    private int age = 40;    //This field gets serialized even though it is private    //because it has the SerializeField attribute applied.    [SerializeField]    private bool hasHealthPotion = true;    void Start()    {        if (hasHealthPotion)            Debug.Log("Person's first name: " + firstName + " Person's age: " + age);    }}
  • SerializeReference 指示Unity序列化字段作为引用。Unity序列化对象时,除非将字段类型派生自[UnityEngine.Object],否则它将序列化所有字段为值类型。默认情况下,不支持多态字段,并且不能原生展示基于引用的拓扑,例如图形。建议从ScriptableObject派生字段类型,因为这通常会导致最佳性能。但是,如果使用ScriptableObjects增加了不可接受的复杂度,则用[SerializeReference]装饰字段会指示Unity按“按引用”而不是“按值”对字段进行序列化。

using System;using System.Collections.Generic;using UnityEngine;public interface IShape {}[Serializable]public class Cube : IShape{    public Vector3 size;}[Serializable]public class Thing{    public int weight;}[ExecuteInEditMode]public class BuildingBlocks : MonoBehaviour{    [SerializeReference]    public List inventory;    [SerializeReference]    public System.Object bin;    [SerializeReference]    public List bins;    void OnEnable()    {        if (inventory == null)        {            inventory = new List()            {                new Cube() {size = new Vector3(1.0f, 1.0f, 1.0f)}            };            Debug.Log("Created list");        }        else            Debug.Log("Read list");        if (bins == null)        {            // This is supported, the 'bins' serialized field is declared as holding a collection type.            bins = new List() { new Cube(), new Thing() };        }        if (bin == null)        {            // !! DO NOT USE !!            // Although, this is syntaxically correct, it is NOT supported as a valid serialization construct because the 'bin' serialized field is declared as holding a single reference type.            bin = new List() { new Cube() };        }    }}
  • SharedBetweenAnimatorsAttribute 指定此StateMachineBehaviour应该只实例化一次,并在所有Animator实例之间共享。此属性减少了每个控制器实例的内存占用量。

using UnityEngine;[SharedBetweenAnimators]public class AttackBehaviour : StateMachineBehaviour{    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)    {        Debug.Log("OnStateEnter");    }}
  • CustomEditor 指定继承自Editor类的自定义编辑器用于哪个运行时类型。

  • CanEditMultipleObjects 用于使CustomEditor支持多对象编辑。

  • DrawGizmo 允许您为任何组件提供Gizmo渲染器。

using UnityEngine;using UnityEditor;public class MyScript : MonoBehaviour{}// The icon has to be stored in Assets/Gizmospublic class MyScriptGizmoDrawer{    [DrawGizmo(GizmoType.Selected | GizmoType.Active)]    static void DrawGizmoForMyScript(MyScript scr, GizmoType gizmoType)    {        Vector3 position = scr.transform.position;        if (Vector3.Distance(position, Camera.current.transform.position) > 10f)            Gizmos.DrawIcon(position, "MyScript Gizmo.tiff");    }}
  • MenuItem 该属性使您可以将菜单项添加到主菜单和Inspector上下文菜单。可以通过% (ctrl on Windows, cmd on macOS), # (shift), & (alt)指定菜单组合快捷键如"MyMenu/Do Something #&g"(shift-alt-g)。也可以使用下划线'_'字符表示非组合快捷键(g)。菜单名与快捷键之间需有一个空格。

  • SettingsProvider 用于注册新的SettingsProvider的属性。使用此属性来装饰一个返回SettingsProvider实例的函数。如果该函数返回null,则Settings窗口中不会显示任何SettingsProvider。

using System.IO;using System.Linq;using UnityEditor;class MyCustomSettingsProvider : SettingsProvider{    const string k_MyCustomSettingsPath = "Resources/MyCustomSettings.asset";    public MyCustomSettingsProvider(string path, SettingsScope scope)        : base(path, scope) {}    public static bool IsSettingsAvailable()    {        return File.Exists(k_MyCustomSettingsPath);    }    [SettingsProvider]    public static SettingsProvider CreateMyCustomSettingsProvider()    {        if (IsSettingsAvailable())        {            return new MyCustomSettingsProvider("MyCustomSettings", SettingsScope.Project);        }        // Settings Asset doesn't exist yet. No need to display anything in the Settings window.        return null;    }}
  • NotKeyableAttribute 在脚本中使用此属性可将字段标记为非动画。

  • FormerlySerializedAs 使用此属性可以重命名字段而不会丢失其序列化值。

using UnityEngine;using UnityEngine.Serialization;public class MyClass : MonoBehaviour{    [FormerlySerializedAs("myValue")]    string m_MyValue;    public string myValue    {        get { return m_MyValue; }        set { m_MyValue = value; }    }}
  • VFXEventAttribute 此类处理用户使用VisualEffect.SendEvent传输到系统的属性。使您可以从Spawn上下文更改初始属性。

优化Inspector类

  • ColorUsageAttribute 在“Color”类型上使用此属性可将“Color字段”和“颜色选择器”配置为显示/隐藏Alpha值,以及是否将该颜色视为HDR颜色还是普通LDR颜色。

  • DelayAttribute 使用此属性时,在用户按下Enter键或将焦点从该字段移开之前,float,int或text字段将不会返回新值。

  • GradientUsageAttribute 该属性用于配置渐变的GradientField和Gradient Editor的用法。

  • HeaderAttribute 使用此PropertyAttribute在Inspector中某些字段上方添加标题。

using UnityEngine;public class Example : MonoBehaviour{    [Header("Health Settings")]    public int health = 0;    public int maxHealth = 100;    [Header("Shield Settings")]    public int shield = 0;    public int maxShield = 0;}
  • HideInInspector 使变量不显示在Inspector中而是被序列化。

using UnityEngine;public class Example : MonoBehaviour{    // Make the variable p not show up in the inspector    // but be serialized.    [HideInInspector]    int p = 5;}
  • InspectorNameAttribute 在枚举值声明中使用此属性可更改Inspector中显示的显示名称。

using UnityEngine;public enum ModelImporterIndexFormat{    Auto = 0,    [InspectorName("16 bits")]    UInt16 = 1,    [InspectorName("32 bits")]    UInt32 = 2,}
  • MinAttribute 用于使脚本中的float或int变量的属性限制为特定的最小值。

  • MultiLineAttribute 用于使用多行文本字段编辑字符串的属性。

  • PropertyAttribute 自定义属性Attribute的基类。使用它为脚本变量创建自定义属性。可以将自定义属性与自定义PropertyDrawer类关联,以控制如何在Inspector中显示具有该属性的脚本变量。

  • RangeAttribute 用于使脚本中的float或int变量的属性限制为特定范围。使用此属性时,float或int会在Inspector中显示为滑块,而不是默认数字字段。

using UnityEngine;public class Example : MonoBehaviour{    // This integer will be shown as a slider,    // with the range of 1 to 6 in the Inspector    [Range(1, 6)]    public int integerRange;    // This float will be shown as a slider,    // with the range of 0.2f to 0.8f in the Inspector    [Range(0.2f, 0.8f)]    public float floatRange;}
  • SpaceAttribute 使用此PropertyAttribute在Inspector中添加一些间距。

using UnityEngine;public class Example : MonoBehaviour{    int health = 0;    int maxHealth = 100;    [Space(10)] // 10 pixels of spacing here.    int shield = 0;    int maxShield = 0;}
  • TextAreaAttribute 用于使用高度灵活且可滚动的文本区域编辑字符串的属性。

using UnityEngine;public class TextAreaExample : MonoBehaviour{    [TextArea]    public string MyTextArea;}
  • ToolTipAttribute 在Inspector窗口中为字段指定工具提示。

  • CustomPreviewAttribute 在Inspector中为指定类型添加额外的预览。

  • CustomPropertyDrawer 指定自定义PropertyDrawer或DecoratorDrawer作为哪个运行时Serializable类或PropertyAttribute的绘制器。

ImageEffect类

  • ImageEffectOpaque 具有此属性的任何ImageEffect将在不透明几何体之后但在透明几何体之前渲染。这允许大量使用深度缓冲区(如SSAO等)的效果仅影响不透明像素。此属性可用于减少具有后处理的场景中的视觉穿帮。

  • ImageEffectAfterScale 具有此属性的任何ImageEffect都将在“动态分辨率”阶段之后呈现。如果希望在动态分辨率放大后再应用图像效果,请添加此属性。这对于那些需要以全分辨率渲染的效果很重要。

  • ImageEffectAllowedInSceneView 如果希望将ImageEffect应用到“场景”视图相机,请添加此属性。效果将应用在相同的位置,并且具有与启用效果的相机相同的值。

  • ImageEffectTransformsToLDR 使用HDR渲染时,有时可能需要在ImageEffect渲染期间切换到LDR渲染。在ImageEffect上使用此属性将使目标缓冲区成为LDR缓冲区,并将其余的Image Effect管道切换为LDR模式。关联此属性是Image Effect的责任,以确保输出在LDR范围内。

  • ImageEffectUseCommandBuffer 使用命令缓冲区实现ImageEffect时,请使用此属性。使用此属性时,Unity会将场景渲染为RenderTexture而不是实际目标。请注意,Camera.forceIntoRenderTexture可能具有相同的效果,但仅在某些情况下。

回调类

  • BeforeRenderOrderAttribute 当应用于方法时,指定在Application.onBeforeRender事件期间调用的顺序。

  • RuntimeInitializeOnLoad 在无需用户操作的情况下初始化运行时类方法。加载游戏后,将调用标记为[RuntimeInitializeOnLoadMethod]的方法。这是在调用Awake方法之后。标记为[RuntimeInitializeOnLoadMethod]的方法的执行顺序无法保证。

// Create a non-MonoBehaviour class which displays// messages when a game is loaded.using UnityEngine;class MyClass{    [RuntimeInitializeOnLoadMethod]    static void OnRuntimeMethodLoad()    {        Debug.Log("After Scene is loaded and game is running");    }    [RuntimeInitializeOnLoadMethod]    static void OnSecondRuntimeMethodLoad()    {        Debug.Log("SecondMethod After Scene is loaded and game is running.");    }}
  • InitializeOnLoadAttribute 允许您在Unity加载时以及在重新编译脚本时初始化Editor类。

  • InitializeOnLoadMethodAttribute 允许在Unity加载时初始化编辑器类方法,而无需用户执行任何操作。

using UnityEngine;using UnityEditor;class MyClass{    [InitializeOnLoadMethod]    static void OnProjectLoadedInEditor()    {        Debug.Log("Project loaded in Unity Editor");    }}
  • InitializeOnEnterPlayModeAttribute 当Unity进入播放模式时,允许初始化编辑器类方法。用于在不重载程序域的情况下在进入播放模式下重置编辑器类中的静态字段。

using UnityEngine;using UnityEditor;class MyAnotherClass{    static int s_MySimpleValue = 0;    [InitializeOnEnterPlayMode]    static void OnEnterPlaymodeInEditor(EnterPlayModeOptions options)    {        Debug.Log("Entering PlayMode");        if (options.HasFlag(EnterPlayModeOptions.DisableDomainReload))            s_MySimpleValue = 0;    }}

程序集

  • AssemblyIsEditorAssembly 程序集级别属性。程序集中具有此属性的所有类都将被视为编辑器类。

  • UnityAPICompatibilityVersionAttribute 声明程序集与特定的Unity API兼容。内部工具使用它来避免处理程序集,以便确定程序集是否正在使用旧的Unity API。

  • AlwaysLinkAssemblyAttribute 确保在托管代码在裁剪时无论是否被其他程序急引用,都始终包含该程序集。

  • PreserveAttribute 防止类,方法,字段或属性在构建时被裁剪。

using UnityEngine;using System.Collections;using System.Reflection;using UnityEngine.Scripting;public class NewBehaviourScript : MonoBehaviour{    void Start()    {        ReflectionExample.InvokeBoinkByReflection();    }}public class ReflectionExample{    static public void InvokeBoinkByReflection()    {        typeof(ReflectionExample).GetMethod("Boink", BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null);    }    // No other code directly references the Boink method, so when when stripping is enabled,    // it will be removed unless the [Preserve] attribute is applied.    [Preserve]    static void Boink()    {        Debug.Log("Boink");    }}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值