Ilingis 发表于 2022-1-5 12:25

Unity教程之-Unity Attribute的使用总结

Attribute是C#的功能,在Unity中可以使用Attribute来给变量和方法增加新的特性或者功能。
举两个例子,在变量上使用特性,可以强制让变量进行序列化,可以在Unity的Editor上进行赋值。
在Class上使用特性,就会在Class的GameObject上自动追加所需的Component。
以下是Unity官网文档中找到的所有Attribute,下面将按照顺序,逐个对这些Attribute进行说明和小的测试。
部分例子使用了Unity官方的示例。
UnityEngine
AddComponentMenu
可以在UnityEditor的Component的Menu中增加自定义的项目。菜单可以设置多级,使用斜线/分隔即可。在Hierarchy中选中GameObject的时候,点击该菜单项,就可以在GameObject上追加该Component。
例如如下代码可以完成下图的效果。
publicclass TestMenu : MonoBehaviour {}
ContextMenu
可以在Inspector的ContextMenu中增加选项。
例如,如下代码的效果
publicclass TestMenu : MonoBehaviour {        void DoSomething () {      Debug.Log ("Perform operation");    }}
ContextMenuItemAttribute
这个属性是Unity4.5之后提供的新功能,可以在Inspector上面对变量追加一个右键菜单,并执行指定的函数。
例子:
publicclass Sample : MonoBehaviour {        publicstring name = "Default";    void ResetName() {      name = "Default";    }}
DisallowMultipleComponent
对一个MonoBehaviour的子类使用这个属性,那么在同一个GameObject上面,最多只能添加一个该Class的实例。
尝试添加多个的时候,会出现下面的提示。


ExecuteInEditMode
默认状态下,MonoBehavior中的Start,Update,OnGUI等方法,需要在Play的状态下才会被执行。
这个属性让Class在Editor模式(非Play模式)下也能执行。
但是与Play模式也有一些区别。
例如:
Update方法只在Scene编辑器中有物体产生变化时,才会被调用。
OnGUI方法只在GameView接收到事件时,才会被调用。
HeaderAttribute
这个属性可以在Inspector中变量的上面增加Header。
例子:
publicclass ExampleClass : MonoBehaviour {        publicint CurrentHP = 0;    publicint MaxHP = 100;        publicint CurrentMP = 0;    publicint MaxMP = 0;}
HideInInspector
在变量上使用这个属性,可以让public的变量在Inspector上隐藏,也就是无法在Editor中进行编辑。
ImageEffectOpaque
在OnRenderImage上使用,可以让渲染顺序在非透明物体之后,透明物体之前。
例子
voidOnRenderImage (RenderTexturesource, RenderTexturedestination){}MultilineAttribute
在string类型上使用,可以在Editor上输入多行文字。
publicclass TestString : MonoBehaviour {        publicstring mText;}

            PropertyAttributeRangeAttribute
在int或者float类型上使用,限制输入值的范围
public class TestRange : MonoBehaviour
{
public int HP;
}
RequireComponent
在Class上使用,添加对另一个Component的依赖。
当该Class被添加到一个GameObject上的时候,如果这个GameObject不含有依赖的Component,会自动添加该Component。
且该Componet不可被移除。
例子
publicclass TestRequireComponet : MonoBehaviour {}
如果尝试移除被依赖的Component,会有如下提示


RPC
在方法上添加该属性,可以网络通信中对该方法进行RPC调用。
void RemoteMethod(){RuntimeInitializeOnLoadMethodAttribute
此属性仅在Unity5上可用。
在游戏启动时,会自动调用添加了该属性的方法。
classMyClass{        staticvoid OnRuntimeMethodLoad ()    {      Debug.Log("Game loaded and is running");    }}SelectionBaseAttribute
当一个GameObject含有使用了该属性的Component的时候,在SceneView中选择该GameObject,Hierarchy上面会自动选中该GameObject的Parent。
SerializeField
在变量上使用该属性,可以强制该变量进行序列化。即可以在Editor上对变量的值进行编辑,即使变量是private的也可以。
在UI开发中经常可见到对private的组件进行强制序列化的用法。
例子
publicclass TestSerializeField : MonoBehaviour {        privatestring name;        private Button _button;}
SharedBetweenAnimatorsAttribute
用于StateMachineBehaviour上,不同的Animator将共享这一个StateMachineBehaviour的实例,可以减少内存占用。
SpaceAttribute
使用该属性可以在Inspector上增加一些空位。 例子:
publicclass TestSpaceAttributeByLvmingbei : MonoBehaviour {    publicint nospace1 = 0;    publicint nospace2 = 0;        publicint space = 0;    publicint nospace3 = 0;}
TextAreaAttribute
该属性可以把string在Inspector上的编辑区变成一个TextArea。
例子:
publicclass TestTextAreaAttributeByLvmingbei : MonoBehaviour {        publicstring mText;}
TooltipAttribute
这个属性可以为变量上生成一条tip,当鼠标指针移动到Inspector上时候显示。
publicclass TestTooltipAttributeByLvmingbei : MonoBehaviour {        publicint year = 0;}

                UnityEngine.SerializationFormerlySerializedAsAttribute
该属性可以令变量以另外的名称进行序列化,并且在变量自身修改名称的时候,不会丢失之前的序列化的值。
例子:
using UnityEngine;using UnityEngine.Serialization;publicclass MyClass : MonoBehaviour {        privatestring m_MyValue;    publicstring myValue    {      get { return m_MyValue; }      set { m_MyValue = value; }    }}CustomPreviewAttribute
将一个class标记为指定类型的自定义预览
Unity4.5以后提供的新功能
例子:
publicclass MyPreview : ObjectPreview{    publicoverrideboolHasPreviewGUI()    {      returntrue;    }    publicoverridevoidOnPreviewGUI(Rect r, GUIStyle background)    {      GUI.Label(r, target.name + " is being previewed");    }}DrawGizmo
可以在Scene视图中显示自定义的Gizmo
下面的例子,是在Scene视图中,当挂有MyScript的GameObject被选中,且距离相机距离超过10的时候,便显示自定义的Gizmo。
Gizmo的图片需要放入Assets/Gizmo目录中。
例子:
可以在Scene视图中显示自定义的Gizmo下面的例子,是在Scene视图中,当挂有MyScript的GameObject被选中,且距离相机距离超过10的时候,便显示自定义的Gizmo。Gizmo的图片需要放入Assets/Gizmo目录中。例子:

InitializeOnLoadAttribute
在Class上使用,可以在Unity启动的时候,运行Editor脚本。
需要该Class拥有静态的构造函数。
做一个创建一个空的gameobject的例子。
例子:
using UnityEditor;using UnityEngine;classMyClass{static MyClass ()    {      EditorApplication.update += Update;      Debug.Log("Up and running");    }    staticvoid Update ()    {      Debug.Log("Updating");    }}MenuItem
在方法上使用,可以在Editor中创建一个菜单项,点击后执行该方法,可以利用该属性做很多扩展功能。 需要方法为static。
例子:
using UnityEngine;using UnityEditor;using System.Collections;publicclass TestMenuItem : MonoBehaviour {        publicstaticvoidCreateGameObject() {      new GameObject("lvmingbei's GameObject");    }}
PreferenceItem
使用该属性可以定制Unity的Preference界面。
在这里就使用官方的例子:
using UnityEngine;using UnityEditor;using System.Collections;publicclass OurPreferences {    // Have we loaded the prefs yetprivatestaticbool prefsLoaded = false;    // The Preferencespublicstaticbool boolPreference = false;    // Add preferences section named "My Preferences" to the Preferences Window        publicstaticvoidPreferencesGUI () {      // Load the preferencesif (!prefsLoaded) {            boolPreference = EditorPrefs.GetBool ("BoolPreferenceKey", false);            prefsLoaded = true;      }      // Preferences GUI      boolPreference = EditorGUILayout.Toggle ("Bool Preference", boolPreference);      // Save the preferencesif (GUI.changed)            EditorPrefs.SetBool ("BoolPreferenceKey", boolPreference);    }}
页: [1]
查看完整版本: Unity教程之-Unity Attribute的使用总结