Unity3D Attributes用法小结(一)

      本文在书写的时候参考了几篇博客,如果有版权问题,还麻烦您私信我!
      本文的Attribute总结,仅仅只小结了UnityEngine命名空间下的Attributes类。本文所讲的Unity各个属性均位于UnityEngine命名空间下面,继承自Attributes类。而UnityEditor命名空间下的Attributes,请参考我另一篇博文Unity3D Attributes用法小结(二)
1.AddComponentMenu 添加组件菜单 用于修饰自定义类

eg:
	//该脚本会被放置于Component菜单栏下的测试 子菜单里面
	using System.Collections;
	using System.Collections.Generic;
	using UnityEngine;

	[AddComponentMenu("测试/AttributeOperation")]
	public class AttributeOperation : MonoBehaviour {

		// Use this for initialization
		void Start () {
			
		}
		
		// Update is called once per frame
		void Update () {
			
		}
	}

效果如图:
这里写图片描述

图1 AddComponentMenu 属性实现图

2.AssemblyIsEditorAssembly
汇编级属性,使用该属性的Class会被认为是EditorClass。具体用法不明。

3.ColorUsageAttribute 用于修饰Color字段 配置取色盘如何显示

eg:
    [ColorUsage(false, true, 1, 1, 1, 1)]
    public Color color;

效果如图所示:
这里写图片描述

图2 ColorUsageAttribute实现图
4.ContextMenu 上下文菜单 可以在Inspector的ContextMenu中增加选项,然后点击齿轮按钮,点击“测试2”,即可触发事件.效果如图
eg:
    [ContextMenu("测试2")]
    void DoSomething()
    {
        Debug.Log("Perform operation");
    }

效果如图所示:
这里写图片描述

图3 ContextMenu 属性实现图
5.ContextMenuItemAttribute 给一个inspector显示的字段添加右键功能,但必须实现功能函数才能右键出来
eg:
	public class Sample : MonoBehaviour {
	    [ContextMenuItem("Reset", "ResetName")]
	    public string name = "Default";
	    void ResetName() {
	        name = "Default";
	    }
	}

效果如图所示:
这里写图片描述

图4 ContextMenuItemAttribute实现图
6.CreateAssetMenuAttribute 用于修饰自定义类 该自定义类需要继承ScriptableObject类,添加到Asset->Create菜单里,这样就能在Asset菜单里Create Asset文件了
eg:
	using System.Collections;
	using System.Collections.Generic;
	using UnityEngine;

	[CreateAssetMenu]
	public class Test1:ScriptableObject
	{
		void DoSomething()
		{
			Debug.Log("Perform operation");
		}
	}

这里写图片描述

图5 CreateAssetMenuAttribute实现图
7.DelayedAttribute 用于修饰字段 整数、浮点数,输入完按了enter或者移出焦点才生效

8.DisallowMultipleComponent 用于修饰自定义类 同一个对象上只允许添加一个该脚本,不允许重复添加
这里写图片描述

图6 DisallowMultipleComponent 属性实现图
9.ExecuteInEditMode       在Editor时执行默认状态下,MonoBehavior中的Start,Update,OnGUI等方法,需要在Play的状态下才会被执行。这个属性让Class在Editor模式(非Play模式)下也能执行。但是与Play模式也有一些区别。例如:Update方法只在Scene编辑器中有物体产生变化时,才会被调用。OnGUI方法只在GameView接收到事件时,才会被调用。
eg:
	using System.Collections;
	using System.Collections.Generic;
	using UnityEngine;

	[ExecuteInEditMode]
	public class PrintAwake : MonoBehaviour
	{
		void Awake()
		{
			Debug.Log("Editor causes this Awake");
		}

		void Update()
		{
			Debug.Log("Editor causes this Update");
		}
	}

10.GUITargetAttribute 用于修饰方法 控制OnGUI方法中的元素,在哪一个相机上显示

eg:
    // Label will appear on display 0 and 1 only
    [GUITarget(0)]//在Game窗口的左上角控制display1显示方法中的label控件
    void OnGUI()
    {
        GUI.Label(new Rect(10, 10, 300, 100), "Visible on TV and Wii U GamePad only");
    }

效果如图所示:

![这里写图片描述](https://img-blog.csdn.net/20170713200211337?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvcXFfMjQ2NDI3NDM=/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
图7 GUITargetAttribute 实现图
11.HeaderAttribute 给字段添加header分类的
eg:
	using UnityEngine;
	using System.Collections;

	public class AttributeOperation: MonoBehaviour {
	   [Header("颜色面板")]
	    [ColorUsage(false, true, 1, 1, 1, 1)]
	    public Color color;
	    
	    [Header("Delayed属性测试")]
	    [Delayed]
	    public int i;
	}

这里写图片描述

图8 HeaderAttribute实现图
12 HelpURLAttribute 类的帮助链接,应该是给右上角的小书用的
eg:
	using UnityEngine;
	using UnityEditor;

	[HelpURL("http://example.com/docs/MyComponent.html")]
	public class MyComponent
	{
	}

13 HideInInspector 修饰字段 在inspector面板中隐藏该字段
eg:
[HideInInspector]
public int p = 5;

14.ImageEffectAllowedInSceneView 图像特效可以在scene视图中显示

15.ImageEffectOpaque 在OnRenderImage上使用,可以让渲染顺序在非透明物体之后,透明物体之前。不透明图像效果优先,优化加速渲染

eg:
	[ImageEffectOpaque]
	void OnRenderImage (RenderTexture source, RenderTexture destination){
	}

16.ImageEffectTransformsToLDR 渲染从从HDR变为LDR 具体使用方法不明。

17.MultilineAttribute 在string类型上使用,可以在Editor上输入多行文字。

eg:
	public class TestString : MonoBehaviour {
		[MultilineAttribute]
		public string mText;
	}

这里写图片描述

图9 MultilineAttribute实现图
18.PreferBinarySerialization 该类优先二进制序列化
eg:
	using UnityEngine;

	// Custom asset type that prefers binary serialization.
	//
	// Create a new asset file by going to "Asset/Create/Custom Data".
	// If you open this new asset in a text editor, you can see how it
	// is not affected by changing the project asset serialization mode.
	//
	[CreateAssetMenu]
	[PreferBinarySerialization]
	public class CustomData : ScriptableObject
	{
		public float[] lotsOfFloatData = new[] { 1f, 2f, 3f };
		public byte[] lotsOfByteData = new byte[] { 4, 5, 6 };
	}

19.PropertyAttribute 使用它来创建脚本变量的自定义属性。

20.RangeAttribute 用于修饰float与int类型字段,使其数字有范围的

21.RequireComponent 自动将所需组件添加为依赖关系。

eg:
	using UnityEngine;

	// PlayerScript requires the GameObject to have a Rigidbody component
	[RequireComponent(typeof(Rigidbody))]
	public class PlayerScript : MonoBehaviour
	{
		Rigidbody rb;

		void Start()
		{
			rb = GetComponent<Rigidbody>();
		}

		void FixedUpdate()
		{
			rb.AddForce(Vector3.up);
		}
	}
  1. RPC 该属性在Unity2017中过时了 在方法上添加该属性,可以网络通信中对该方法进行RPC调用。
eg:
	[RPC]
	void RemoteMethod(){
	}

23.RuntimeInitializeOnLoadMethodAttribute 在游戏启动时,会自动依次调用添加了该属性的方法。

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

24.SelectionBaseAttribute 当一个GameObject含有使用了该属性的Component的时候,在SceneView中选择该GameObject,Hierarchy上面会自动选中该GameObject的Parent。

eg:
	[SelectionBase]
	public class PlayerScript : MonoBehaviour {

	}

25.SerializeField 在变量上使用该属性,可以强制该变量进行序列化。即可以在Editor上对变量的值进行编辑,即使变量是private的也可以。在UI开发中经常可见到对private的组件进行强制序列化的用法。

eg:
	public class TestSerializeField : MonoBehaviour {
		[SerializeField]
		private string name;

		[SerializeField]
		private Button _button;
	}

26.SharedBetweenAnimatorsAttribute 用于StateMachineBehaviour上,不同的Animator将共享这一个StateMachineBehaviour的实例,可以减少内存占用。

eg:
	using UnityEngine;

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

27.SpaceAttribute 使用该属性可以在Inspector上增加一些空位。

eg:
	using UnityEngine;
	using System.Collections;

	public class ExampleClass : MonoBehaviour {
		public int health = 0;
		public int maxHealth = 100;
		[Space(10)]//上下属性之间隔了10个空位
		public int shield = 0;
		public int maxShield = 0;
	}

28.TextAreaAttribute 该属性可以把string在Inspector上的编辑区变成一个TextArea。

eg:
	using UnityEngine;

	public class TextAreaExample : MonoBehaviour
	{
		[TextArea]
		public string MyTextArea;
	}

这里写图片描述

图10 TextAreaAttribute 实现图
29.TooltipAttribute 这个属性可以为变量上生成一条提示信息,当鼠标指针移动到Inspector上时候会显示
eg:
	public class TestTooltipAttributeTest : MonoBehaviour {
		[Tooltip("This year is 2017!")]
		public int year = 0;
	}

这里写图片描述

图11 TooltipAttribute 实现图
30.UnityAPICompatibilityVersionAttribute 用来声明API的版本兼容性

总结:上述大部分属性都是针对Inspector面板进行二次开发的,也有少部分是针对Unity工作栏中开发的。熟悉常用的即可!

文中若有理解不对的地方,欢迎指正!如有疑问,欢迎留言!

本文书写参考连接:
(1)http://www.unity.5helpyou.com/3550.html
(2)http://www.cnblogs.com/ptqueen/p/6626687.html
(3)https://docs.unity3d.com/ScriptReference/AddComponentMenu.html

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值