UnityEngine、UnityEditor中的所有 Attributes

(持续更新)

UnityEngine中的Attributes


如果这个Attribute不需要传入参数,那么加不加括号好像都可以(具体去学C#的AttributeUsage)

AddComponentMenu

//给自定义的组件添加到Component/Custom/XX路径,取代原本的Component/Scripts/xxx

[AddComponentMenu("Custom/xx")]		
public class XX : MonoBehaviour{ }

RequireComponent

//自动添加依赖的组件

[RequireComponent(typeof(Rigidbody))]
public class PlayerScript : MonoBehaviour{ }

AssemblysEditorAssembly (?)

//Assembly level attribute. Any classes in an assembly with this attribute 
//will be considered to be Editor Classes.

BeforeRenderOrder (?)

//Use this BeforeRenderOrderAttribute 
//when you need to specify a custom callback order for Application.onBeforeRender.

//Application.onBeforeRender will reorder all registered events recievers and call them in order,
//from lowest to highest, based on this attribute. No attribute represents an order of 0.

ColorUsage


//Attribute for Color fields. Used for configuring the GUI for the color.

public ColorUsageAttribute(bool showAlpha);
public ColorUsageAttribute(bool showAlpha, bool hdr, float minBrightness, float maxBrightness, 
				float minExposureValue, float maxExposureValue); 

//用于配置 ColorField 和 Color Picker

//Use this attribute on a Color to configure the Color Field and Color Picker 
//to show/hide the alpha value 
//and whether to treat the color as a HDR color or as a normal LDR color.

//用此属性配置“颜色字段”和“颜色选择器”,以显示/隐藏alpha值,
//以及是将该颜色视为HDR颜色还是将其视为正常的LDR颜色。

/*
	hdr :如果设为true,则看作一个HDR颜色
	maxBrightness :当使用HDR color picker时,允许的最大值
	maxExposureValue :当使用HDR color picker时,允许的最大exposure value
	minBrightness : .......
	minExposureValue : ......
	showAlpha :如果设为false,那么 ColorField中的alpha栏隐藏,并且alpha值不显示在 Color Picker上
*/

	[ColorUsage(true,true,0,10,0,10)]
	public Color color;
	

这里写图片描述

##ContextMenu

//为组件 Inspector中的 Context menu 添加命令(函数),注意函数只能是“非静态函数”

public class Test : MonoBehaviour 
{
	[ContextMenu("Do Something from ContextMenu")]
	void DoSomething()
	{
		Debug.Log ("perform operation by clicking the context menu");
	}
}

这里写图片描述

##ContextMenuItem

//给组件Inspector中的某个属性,添加右键操作(函数),注意该函数是 非静态函数
	[ContextMenuItem("Reset", "ResetBiography")]
	[Multiline(8)]
	public string playerBiography = "";

	void ResetBiography() {
		playerBiography = "";
	}

这里写图片描述

##CreateAssetMenu(重点)

//用于创建自定义的ScriptableObject,具体为.asset 资源
//支持在 Asset/Create/xx,也支持在 工程视图右键
//同名的资源,会自动更改名称

[CreateAssetMenu(fileName="skill",menuName="skill Data",order=1)]
public class MyAsset : ScriptableObject { }

这里写图片描述

##CustomGridBrush (?)

##Delayed

//用于标记一个 float、int、string 类型的变量,
//测试结果是,在Inspector上不能通过拖动来改变值的大小,输入框需要回车或是鼠标焦点离开输入框才改变值
//所以这是给自己找麻烦,没啥用处

[Delayed]
public float fl = 9.0f;

##DisallowMultiple

//防止同类型(或子类型)给一个gameobject添加多次
[DisallowMultipleComponent]
public class Test : MonoBehaviour { }

这里写图片描述

##ExecuteInEditMode (重点)

另外,查阅 MonoBehaviour 的 runInEditMode 属性,public bool runInEditMode;

//放在类定义之前,使脚本实例在编辑模式也会运行
//默认情况下,MonoBehaviour只会在play mode执行,(全部还是部分回调函数?)

// the functions are not called constantly like they are in play mode
//Awake :载入新场景时
//Update:场景中某个东西发生变化时(不一定要这个附加脚本的对象,对吧。。。)
//OnGUI : Game View 接收到一个事件(Event)时调用
//OnRenderObject 及其他 rendering callback :scene view 或 game view的每一次重绘都会调用

[ExecuteInEditMode]
public class Test : MonoBehaviour { }

##GUITarget (?)

//Allows to control for which display the OnGUI is called.
    
public class ExampleClass : MonoBehaviour
{
    // Label will appear on display 0 and 1 only
    [GUITarget(0, 1)]
    void OnGUI()
    {
        GUI.Label(new Rect(10, 10, 300, 100), "Visible on TV and Wii U GamePad only");
    }
}

##Header

//Use this PropertyAttribute to add a header above some fields in the Inspector.
//The header is done using a DecoratorDrawer.(这两句不用理)

public class Test : MonoBehaviour 
{
	[Header("Health settings")]
	public int health = 0;
	public int maxHealth = 100;

	[Header("Shield Settings")]
	public int shield = 0;
	public int maxShield = 100;
}

这里写图片描述

##HelpURL

如果真要点击一个按钮,或其他东西,来打开一个URL,可以用

Application.OpenURL("...");
//Provide a custom documentation URL for a class.
//因为多数情况下都不会通过这个来打开链接,所以没啥用

[HelpURL("https://www.csdn.net/")]
public class Test : MonoBehaviour { }

这里写图片描述

##HideInInspector

//使属性可以序列化但是不显示在Inspector上
public class Test : MonoBehaviour 
{
	[HideInInspector]
	public int p  =5;
}

##ImageEffectAfterScale (待完成)
##ImageEffectAllowdInSceneView
##ImageEffectOpaque
##ImageEffectTransformsToLDR
.

##Multiline (另外参考 TextArea)

//用于标记 string 类型变量
public class Test : MonoBehaviour 
{
	[Multiline]
	public string str1;

	[Multiline(9)]
	public string str2;
}

这里写图片描述

##TextArea (另外参考 Multiline)

//用于修饰string变量,高度可变,出现一个滚动条
//可以指定最小最大行数

public class Test : MonoBehaviour
{
	[TextArea]
	public string str1;

	[TextArea(3,10)]        //限定Inspector不用滚动条,就能显示的最小最大行数
	public string str2;
}


这里写图片描述

##PreferBinarySerialization (?)

##Property(基类,不用理)

//PropertyAttribute是个抽象类,是其他一些 xxAttribute 类的基类,所以一般不会直接用这个东西

//Base class to derive custom property attributes from. 
//Use this to create custom attributes for script variables.

//A custom attributes can be hooked up with a custom PropertyDrawer class 
//to control how a script variable with that attribute is shown in the Inspector.

##Range

//用于标记 float 或 int 变量,限定在一个范围,Inspector出现一个 slider

public class Test : MonoBehaviour 
{
	[Range(1.0f,5.0f)]
	public float fl;

	[Range(0,10)]
	public int i;
}

这里写图片描述

//说点题外话
//这个RangeAttribute虽然可以修饰int型变量,但是它自身的构造函数参数类型只有float类型

namespace UnityEngine
{
	[AttributeUsage (AttributeTargets.Field, Inherited = true, AllowMultiple = false)]
	public sealed class RangeAttribute : PropertyAttribute
	{
		public readonly float min;

		public readonly float max;

		public RangeAttribute (float min, float max);
	}
}

##RPC

//用于设置 RPC 函数,已过时,不用理

##RuntimeInitializeOnLoadMethod(有用)

//在游戏加载的时候,允许一个运行时类方法(静态方法)被初始化,不需要用户调用
//游戏加载之后,所有Awake之后,Start之前,标记了 [RuntimeInitializeOnLoadMethod] 的方法会被 invoked

//注意:
//Awake、Start、Update之类的方法不能标记 [RuntimeInitializeOnLoadMethod]
//必须是静态方法才会调用
//这些静态方法,不一定要在继承MonoBehaviour的类中


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.");
	}
}


##SelectionBase (?)

Add this attribute to a script class to /mark its GameObject as a selection base object/ for Scene View picking.
.
In the Unity Scene View, when clicking to select objects, Unity will try to figure out the best object to select for you.
.
If you click on an object that is part of a prefab,
the root of the prefab is selected,because a prefab root is treated as a selection base.
.
You can make other objects be treated as selection base too.
You need to create a script class with the SelectionBase attribute,
and then you need to add that script to the GameObject.

##SerializeField

//文档中讲了很多内容,不想翻译,大致看看
//https://docs.unity3d.com/ScriptReference/SerializeField.html
//注意:unity不会序列化字典

//强制序列化一个private字段(protected字段),使之显示在Inspector上

[SerializeField]
private bool isShoe = true;

##ShadredBetweenAnimators( ? 动画系统 )

SharedBetweenAnimatorsAttribute is an attribute that specify that this StateMachineBehaviour should be instantiate only once and shared among all Animator instance. This attribute reduce the memory footprint for each controller instance.
.
It’s up to the programmer to choose which StateMachineBehaviour could use this attribute.
Be aware that if your StateMachineBehaviour change some member variable
it will affect all other Animator instance using it. See Also: StateMachineBehaviour class.

什么是 StateMachineBehaviour ?
https://docs.unity3d.com/ScriptReference/StateMachineBehaviour.html

//指定 StateMachineBehaviour 只被实例化一次,然后在所有Animator实例之间共享

using UnityEngine;

[SharedBetweenAnimators]
public class AttackBehaviour : StateMachineBehaviour
{
    public override void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex)
    {
        Debug.Log("OnStateEnter");
    }
}

##Space

//在Inspector中,这个属性与上一个的属性之间隔开一定的距离
//The spacing is done using a DecoratorDrawer.

public class ExampleClass : MonoBehaviour 
{
    public int health = 0;
    public int maxHealth = 100;
    [Space(10)]
    public int shield = 0;
    public int maxShield = 0;
}

这里写图片描述

##Tooltip

//当鼠标指向Inspector上这个变量,会提示这条帮助信息

public class Test : MonoBehaviour
{
	[Tooltip("show some msg")]
	public int i;
}

##UnityAPICompatibilityVersion

//应该是unity内部工具使用的,用于指定Assemblies使用的 Unity API版本,所以几乎不必关注......






UnityEditor中的Attributes

##CallbackOrder (?)

Base class for Attributes that require a callback index.

##CanEditMultipleObjects

使一个Custom Editor可以支持多物体同时编辑
当选择了多个物体,没有这个Attribute的编辑器,不支持多物体编辑,就会显示信息“Multi-object editing not supported”

##CustomEditor

CustomEditor 是个自定义 Inspector,
Tells an Editor class which run-time type it’s an editor for.
When you make a custom editor for a component, you need put this attribute on the editor class.

public CustomEditor(Type inspectedType);
public CustomEditor(Type inspectedType, bool editorForChildClasses); 

##CustomEditorForRenderPipeline (?)

Tells an Editor class which run-time type it’s an editor for when the given RenderPipeline is activated.

When you make a custom editor for a component that changes based on the active RenderPipeline you need to put this attribute on the class.

public CustomEditorForRenderPipelineAttribute(Type inspectedType, Type renderPipeline);
public CustomEditorForRenderPipelineAttribute(Type inspectedType, Type renderPipeline, bool editorForChildClasses); 

##CustomPreview

Adds an extra preview in the Inspector for the specified type.
You can use this attribute to add your custom preview to any object that can be Inspected.
.
为指定的类型,在Inspector中添加一个额外的 preview
可以为任意能够被Inspected的物体添加这个属性

public CustomPreviewAttribute(Type type); 

##CustomPropertyDrawer

Tells a custom PropertyDrawer or DecoratorDrawer which run-time Serializable class or PropertyAttribute it’s a drawer for.
.
When you make a custom PropertyDrawer or DecoratorDrawer, you need put this attribute on the drawer class.
.
If the drawer is for a Serializable class, then pass the type of the class to the CustomPropertyDrawer attribute (only valid for PropertyDrawers; not DecoratorDrawers).
.
If the drawer is for a PropertyAttribute, then pass the type of the PropertyAttribute to the CustomPropertyDrawer attribute.

public CustomPropertyDrawer(Type type);
public CustomPropertyDrawer(Type type, bool useForChildren); 

##DrawGizmo

The DrawGizmo attribute allows you to supply a gizmo renderer for any Component.
允许为任意组件提供一个gizmo renderer

The renderer function must be static, and take two parameters: the object for which the gizmo is being drawn, and a GizmoType parameter which indicates the context in which the gizmo is being drawn.
渲染gizmo的函数必须是静态函数,并且带两个参数:
(1)gizmo渲染的物体(继承MonoBehaviour的脚本类型)
(2)GizmoType

The renderer function can be defined in any class, including editor scripts. This allows you to keep your gizmo-drawing code out of your component scripts so that it is not included in builds.
渲染gizmo的函数可以定义在任意类中,包括编辑器脚本。
这允许你将绘制gizmo的脚本和component脚本分离,然后这部分就不会被打包。

using UnityEngine;
using UnityEditor;

public class MyScript : MonoBehaviour
{
}

// The icon has to be stored in Assets/Gizmos

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, "MyScript Gizmo.tiff");
	}
}

##InitializeOnLoad

Allow an editor class to be initialized when Unity loads without action from the user.
.
Note that static constructors with this attribute are called when Unity starts and when Run is pressed. In this second case the Unity runtime is intialised and this is treated as a Load.
.
See the manual page about running editor code on launch for further details.

https://docs.unity3d.com/Manual/RunningEditorCodeOnLaunch.html

using UnityEngine;
using UnityEditor;

[InitializeOnLoad]
public class Startup {
    static Startup()
    {
        Debug.Log("Up and running");
    }
}
using UnityEditor;
using UnityEngine;

[InitializeOnLoad]
class MyClass
{
    static MyClass ()
    {
        EditorApplication.update += Update;
    }

    static void Update ()
    {
        Debug.Log("Updating");
    }
}

##InitializeOnLoadMethod

//Allow an editor class method to be initialized when Unity loads without action from the user.

using UnityEngine;
using UnityEditor;

class MyClass
{
    [InitializeOnLoadMethod]
    static void OnProjectLoadedInEditor()
    {
        Debug.Log("Project loaded in Unity Editor");
    }
}

##MenuItem

//https://docs.unity3d.com/ScriptReference/MenuItem.html
//多种用法、快捷键、验证是否可用

[MenuItem("Tools/xx")]
static void Do(){ }

 
 
    // 验证是否可用
    
    [MenuItem("MyMenu/Log Selected Transform Name")]
    static void LogSelectedTransformName()
    {
        Debug.Log("Selected Transform is on " + Selection.activeTransform.gameObject.name + ".");
    }
    
    [MenuItem("MyMenu/Log Selected Transform Name", true)]
    static bool ValidateLogSelectedTransformName()
    {
        // Return false if no transform is selected.
        return Selection.activeTransform != null;
    }

public MenuItem(string itemName);
public MenuItem(string itemName, bool isValidateFunction);
public MenuItem(string itemName, bool isValidateFunction, int priority); 

##PreferenceItem

//Edit -> Preferences...

//The PreferenceItem attribute allows you to add preferences sections to the Preferences Window.

//The PreferenceItem attribute turns any static function into an OnGUI callback. 
//Only static functions can use the PreferenceItem attribute.

using UnityEngine;
using UnityEditor;

public class ExampleScript : MonoBehaviour
{
    // 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);
    }
}

这里写图片描述

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值