Unity 常用attributes整理
发表于2018-03-08
本篇文章给大家整理了常用的attributes,以帮助大家掌握与attributes相关的知识。
Serializable:可以让子类(继承类)的变量属性显示在检视面板中,也能序列化它。
//SerializableTest.cs [System.Serializable] public class SerializableTest { public int p = 5; public Color c = Color.white; } //SerializableTest2.cs public class SerializableTest2 : MonoBehaviour { public SerializableTest test; }
SerializeField:在变量上使用该属性,可以强制该变量进行序列化。即可以在Editor上对变量的值进行编辑,即使变量是private的也可以。
在UI开发中经常可见到对private的组件进行强制序列化的用法。或将数据存入prefab。
public class TestSerializeField : MonoBehaviour { [SerializeField] private string name; [SerializeField] private Button _button; }
MenuItem:在方法上使用,可以在Editor中创建一个菜单项,点击后执行该方法,可以利用该属性做很多扩展功能。 需要方法为static。
public class TestMenuItem : MonoBehaviour { [MenuItem ("MyMenu/Create GameObject")] public static void CreateGameObject() { new GameObject("lvmingbei's GameObject"); } }
TooltipAttribute:这个属性可以为变量上生成一条tip,当鼠标指针移动到Inspector上时候显示。
public class TestTooltipAttributeByLvmingbei : MonoBehaviour { [Tooltip("This year is 2016!")] public int year = 0; }
AddComponentMenu :可以在UnityEditor的Component的Menu中增加自定义的项目。
[AddComponentMenu("TestMenu/TestComponet")] public class TestMenu : MonoBehaviour { }
ContextMenu:可以在Inspector的ContextMenu中增加选项。
public class TestMenu : MonoBehaviour { [ContextMenu ("Do Something")] void DoSomething () { Debug.Log ("Perform operation"); } }
ContextMenuItemAttribute:Unity4.5之后提供的新功能,可以在Inspector上面对变量追加一个右键菜单,并执行指定的函数。
public class Sample : MonoBehaviour { [ContextMenuItem("Reset", "ResetName")] public string name = "Default"; void ResetName() { name = "Default"; } }
DisallowMultipleComponent:对一个脚本使用这个属性,那么在同一个GameObject上面,只能挂载一个该脚本。
HeaderAttribute:这个属性可以在Inspector中变量的上面增加Header。
public class ExampleClass : MonoBehaviour { [Header("生命值")] public int CurrentHP = 0; public int MaxHP = 100; [Header("魔法值")] public int CurrentMP = 0; public int MaxMP = 0; }
HideInInspector:在变量上使用这个属性,可以让public的变量在Inspector上隐藏,也就是无法在Editor中进行编辑
RangeAttribute:在int或者float类型上使用,限制输入值的范围
public class TestRange : MonoBehaviour { [Range(0, 100)] public int HP; }
RequireComponent:在脚本使用,添加对另一个脚本的依赖。如果这个GameObject不含有依赖的组件,会自动添加该组件。
[RequireComponent(typeof(Rigidbody))] public class TestRequireComponet : MonoBehaviour { }
SerializeField:在变量上使用该属性,可以强制该变量进行序列化。即可以在Editor上对变量的值进行编辑,即使变量是private的也可以。
在UI开发中经常可见到对private的组件进行强制序列化的用法。或将数据存入prefab。
public class TestSerializeField : MonoBehaviour { [SerializeField] private string name; [SerializeField] private Button _button; }
MultilineAttribute:在string类型上使用,可以在Editor上输入多行文字。
public class TestString : MonoBehaviour { [MultilineAttribute] public string mText; }
ExecuteInEditMode:默认状态下,MonoBehavior中的Start,Update,OnGUI等方法,需要在Play的状态下才会被执行。这个属性让脚本在Editor模式(非Play模式)下也能执行。但是与Play模式也有一些区别。例如:Update方法只在Scene编辑器中有物体产生变化时,才会被调用。OnGUI方法只在GameView接收到事件时,才会被调用。
RuntimeInitializeOnLoadMethodAttribute:此属性仅在Unity5上可用。在游戏启动时,会自动调用添加了该属性的方法。
class MyClass { [RuntimeInitializeOnLoadMethod] static void OnRuntimeMethodLoad () { Debug.Log("Game loaded and is running"); } }
SelectionBaseAttribute:当一个GameObject含有使用了该属性的Component的时候,在SceneView中选择该GameObject,Hierarchy上面会自动选中该GameObject的Parent。
SharedBetweenAnimatorsAttribute:用于StateMachineBehaviour上,不同的Animator将共享这一个StateMachineBehaviour的实例,可以减少内存占用。
SpaceAttribute:使用该属性可以在Inspector上增加一些空位。
public class TestSpaceAttributeByLvmingbei : MonoBehaviour { public int nospace1 = 0; public int nospace2 = 0; [Space(10)] public int space = 0; public int nospace3 = 0; }
TextAreaAttribute:该属性可以把string在Inspector上的编辑区变成一个TextArea。
public class TestTextAreaAttributeByLvmingbei : MonoBehaviour { [TextArea] public string mText; }
TooltipAttribute:这个属性可以为变量上生成一条tip,当鼠标指针移动到Inspector上时候显示。
public class TestTooltipAttributeByLvmingbei : MonoBehaviour { [Tooltip("This year is 2016!")] public int year = 0; } CustomPreviewAttribute:Unity4.5以后提供的新功能。将一个class标记为指定类型的自定义预览。 [CustomPreview(typeof(GameObject))] public class MyPreview : ObjectPreview { public override bool HasPreviewGUI() { return true; } public override void OnPreviewGUI(Rect r, GUIStyle background) { GUI.Label(r, target.name + " is being previewed"); } }
CustomPreviewAttribute:Unity4.5以后提供的新功能。将一个class标记为指定类型的自定义预览。
DrawGizmo:可以在Scene视图中显示自定义的Gizmo。下面的例子,是在Scene视图中,当挂有MyScript的GameObject被选中,且距离相机距离超过10的时候,便显示自定义的Gizmo。Gizmo的图片需要放入Assets/Gizmo目录中。
public class MyScript : MonoBehaviour { } public 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, "300px-Gizmo.png"); } }
InitializeOnLoadAttribute:在Class上使用,可以在Unity启动的时候,运行Editor脚本。需要该Class拥有静态的构造函数。
[InitializeOnLoad] class MyClass { static MyClass () { EditorApplication.update += Update; Debug.Log("Up and running"); } static void Update () { Debug.Log("Updating"); } }
InitializeOnLoadMethodAttribute:在Method上使用,是InitializeOnLoad的Method版本。Method必须是static的。
PreferenceItem:使用该属性可以定制Unity的Preference界面。
public class OurPreferences { // Have we loaded the prefs yet private static bool prefsLoaded = false; // The Preferences public static bool boolPreference = false; // Add preferences section named "My Preferences" to the Preferences Window [PreferenceItem ("My Preferences")] public static void PreferencesGUI () { // Load the preferences if (!prefsLoaded) { boolPreference = EditorPrefs.GetBool ("BoolPreferenceKey", false); prefsLoaded = true; } // Preferences GUI boolPreference = EditorGUILayout.Toggle ("Bool Preference", boolPreference); // Save the preferences if (GUI.changed) EditorPrefs.SetBool ("BoolPreferenceKey", boolPreference); } }
OnOpenAssetAttribute:在打开一个Asset后被调用。
public class MyAssetHandler { [OnOpenAssetAttribute(1)] public static bool step1(int instanceID, int line) { string name = EditorUtility.InstanceIDToObject(instanceID).name; Debug.Log("Open Asset step: 1 ("+name+")"); return false; // we did not handle the open } // step2 has an attribute with index 2, so will be called after step1 [OnOpenAssetAttribute(2)] public static bool step2(int instanceID, int line) { Debug.Log("Open Asset step: 2 ("+instanceID+")"); return false; // we did not handle the open } }
PostProcessBuildAttribute:该属性是在build完成后,被调用的callback。同时具有多个的时候,可以指定先后顺序。
public class MyBuildPostprocessor { [PostProcessBuildAttribute(1)] public static void OnPostprocessBuild(BuildTarget target, string pathToBuiltProject) { Debug.Log( pathToBuiltProject ); } }