天天看點

unity 常用/有用attributes

多個attributes逗号隔開,[SerializeField,Tooltip("This year is 2016!")]

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

    }

}

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

        }

}