1. 程式人生 > >[轉]Unity3D Attributes用法小結

[轉]Unity3D Attributes用法小結

原博:https://blog.csdn.net/qq_24642743/article/details/75092091

本文在書寫的時候參考了幾篇部落格,如果有版權問題,還麻煩您私信我! 
      本文的Attribute總結,僅僅只小結了UnityEngine名稱空間下的Attributes類。後續還有UnityEditor名稱空間下的Attributes,這部分有時間再繼續小結。Unity各個屬性位於UnityEngine名稱空間下面,繼承自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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

效果如圖: 


這裡寫圖片描述

 

圖1 AddComponentMenu 屬性實現圖


2.AssemblyIsEditorAssembly 
彙編級屬性,使用該屬性的Class會被認為是EditorClass。具體用法不明。

 

3.ColorUsageAttribute 用於修飾Color欄位 配置取色盤如何顯示

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

效果如圖所示: 


這裡寫圖片描述

 

圖2 ColorUsageAttribute實現圖


4.ContextMenu 上下文選單 
可以在Inspector的ContextMenu中增加選項,然後點選齒輪按鈕,點選“測試2”,即可觸發事件.效果如圖

 

eg:
    [ContextMenu("測試2")]
    void DoSomething()
    {
        Debug.Log("Perform operation");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

效果如圖所示: 

這裡寫圖片描述

 

圖3 ContextMenu 屬性實現圖


5.ContextMenuItemAttribute 給一個inspector顯示的欄位新增右鍵功能,但必須實現功能函式才能右鍵出來

 

eg:
    public class Sample : MonoBehaviour {
        [ContextMenuItem("Reset", "ResetName")]
        public string name = "Default";
        void ResetName() {
            name = "Default";
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

效果如圖所示: 

這裡寫圖片描述

 

圖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");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

 

這裡寫圖片描述

 

圖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");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

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");
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

效果如圖所示: 

這裡寫圖片描述

 

圖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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

 

這裡寫圖片描述

 

圖8 HeaderAttribute實現圖


12 HelpURLAttribute 類的幫助連結,應該是給右上角的小書用的

 

eg:
    using UnityEngine;
    using UnityEditor;

    [HelpURL("http://example.com/docs/MyComponent.html")]
    public class MyComponent
    {
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

13 HideInInspector 修飾字段 在inspector面板中隱藏該欄位 
eg: 
[HideInInspector] 
public int p = 5;

14.ImageEffectAllowedInSceneView 影象特效可以在scene檢視中顯示

15.ImageEffectOpaque 在OnRenderImage上使用,可以讓渲染順序在非透明物體之後,透明物體之前。不透明影象效果優先,優化加速渲染

eg:
    [ImageEffectOpaque]
    void OnRenderImage (RenderTexture source, RenderTexture destination){
    }
  • 1
  • 2
  • 3
  • 4

16.ImageEffectTransformsToLDR 渲染從從HDR變為LDR 具體使用方法不明。

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

eg:
    public class TestString : MonoBehaviour {
        [MultilineAttribute]
        public string mText;
    }
  • 1
  • 2
  • 3
  • 4
  • 5

 

這裡寫圖片描述

 

圖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 };
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

22 RPC 該屬性在Unity2017中過時了 在方法上新增該屬性,可以網路通訊中對該方法進行RPC呼叫。

eg:
    [RPC]
    void RemoteMethod(){
    }
  • 1
  • 2
  • 3
  • 4

22.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.");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

23.SelectionBaseAttribute 當一個GameObject含有使用了該屬性的Component的時候,在SceneView中選擇該GameObject,Hierarchy上面會自動選中該GameObject的Parent。

eg:
    [SelectionBase]
    public class PlayerScript : MonoBehaviour {

    }
  • 1
  • 2
  • 3
  • 4
  • 5

24.SerializeField 在變數上使用該屬性,可以強制該變數進行序列化。即可以在Editor上對變數的值進行編輯,即使變數是private的也可以。在UI開發中經常可見到對private的元件進行強制序列化的用法。

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

        [SerializeField]
        private Button _button;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

25.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");
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

26.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;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

27.TextAreaAttribute 該屬性可以把string在Inspector上的編輯區變成一個TextArea。

eg:
    using UnityEngine;

    public class TextAreaExample : MonoBehaviour
    {
        [TextArea]
        public string MyTextArea;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

 

這裡寫圖片描述

 

圖10 TextAreaAttribute 實現圖


28.TooltipAttribute 這個屬性可以為變數上生成一條提示資訊,當滑鼠指標移動到Inspector上時候會顯示

 

eg:
    public class TestTooltipAttributeTest : MonoBehaviour {
        [Tooltip("This year is 2017!")]
        public int year = 0;
    }
  • 1
  • 2
  • 3
  • 4
  • 5

 

這裡寫圖片描述

 

圖11 TooltipAttribute 實現圖


29.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