您的位置:首页 > 移动开发 > Unity3D

unity中的[xxxxxx]特性(Attributes)

2015-08-19 19:59 330 查看
[SerializeField] 在Inspector版面中显示非public属性,并且序列化;若写在public前面,等于没写。

[Obsolete("调用提示信息")]

[NonSerialized]在Inspector版面中隐藏public属性,并且序列化;如果写在非public属性前面,等于没写。

[HideInInspector] 在Inspector版面中隐藏public属性,与上面相比,只是隐藏,没有序不序列化的功能。

[AddComponentMenu("XXX/XX/XXX")] 让Component菜单下出现你自定义的类,位置是“XXX/XX/XXX”,至于功能么,用过Component的都知道,不用解释了吧。

[ExecuteInEditMode] 在编辑界面让你的功能(类)起作用,就是你不用点开始,就可你让你的功能起作用,打个比方,NGUI里面的Slider的滑动条就是酱紫。

[RequireComponent (typeof (ClassName))] 就是在你把被这句话标记的类拖到(或者AddComponent)GameObject上时,自动再给你加上“ClassName”这个类。

[ContextMenu ("XXX")] 在Inspector版面中,右击包含这条标记的类,在菜单中会出现名为“XXX”的选项,点击选项,会执行被标记的功能 注:此乃标记功能也,非标记类。

[MenuItem ("XXX/XXX")] 在菜单中出现选项栏,点一下,执行对应功能。注:对应的功能必须是static,同时,使用的时候需要加上using UnityEditor,这个类也要找个Editor文件夹放(一般放“Assets\Editor”),要不……就等着纠结吧。

1.AddComponentMenu 添加组件菜单

这函数只是起方便用,原本的脚本(组建)都会在“Component/Script”菜单下,在类之前声明一下这个,它便可以出现在"Componet"菜单下的任何位置。说明指的是要重启U3D才能显示,不过测试貌似直接可以显示。

[AddComponentMenu("MyPhysic/PhysicType")]

public class PhysicType: MonoBehaviour

{

}

2.ContextMenu 上下文菜单

这个译名我觉得很不自然,其实上下文算是啥东西……这个函数是在Inspector的脚本中加一个触发事件,就是删除脚本重置脚本按钮的那个小拉菜单中,具体很难说清位置,所以我截了个图。

public class Attributes : MonoBehaviour {

[ContextMenu("Hello World!")]

void HelloWorld()

{

Debug.Log("Hello World!");

}

}

3.ExecuteInEditMode 在Editor模式下运行

跟名字一样,在编辑器中运行。不过有三种函数的调用方式。

a- "Update()" is only called when something in the scene changed.

b- "OnGUI()" is called when the Game View recieves an Event.

c- "OnRenderObject()" and the other rendering callback functions are called on every repaint of the Scene View or Game View.

[ExecuteInEditMode]

public class ExecuteInEditModeTest: MonoBehaviour

{

private Vector3 vec_Rotation = new Vector3(0.0f, 0.5f, 0.0f);

//Rotate all the time

void OnRenderObject()

{

transform.Rotate(vec_Rotation);

}

}

4.HideInInspector 在检视面板中隐藏

public class HideInspectorTest : MonoBehaviour

{

[HideInInspector]

public Transform m_Target;

void Start()

{

m_Target = GameObject.Find("test").transform;

}

}

5.RequireComponent 必须要有相应的组建

加入一个组建之前必须存在另一个相应的组建,若没有则自动创建。这个在项目中非常有必要用到,尤其是项目人员比较多的时候(大于三四个)。

[RequireComponent (typeof (Rigidbody))]

public class RequireComponentTest : MonoBehaviour {

void FixedUpdate() {

rigidbody.AddForce(Vector3.up);

}

}

6.NonSerialized 不被序列化

不被序列化该变量,且不显示在检视面板中。

public class Test {

[System.NonSerialized]

public int i_Helloword = 5;

}

7.Serializable 可序列化

这个属性可以让子类(继承类)的变量属性显示在检视面板中,也能序列化它。(JS的话完全不需要这个属性。)

//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;

}

8.SerializeField 序列化域(强制序列化)

这里写得比较清楚,可以将私有变量序列化,将U3D的内建变量序列化等。
http://game.ceeger.com/Script/Attributes/SerializeField.html
另外,关于[NonSerialized]和[RPC],理解起来比较麻烦,也不是很常用,就算了……
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: