什麼是Attribute?
Attribute
(屬性)是C#獨有的語法特性。
可以在一個Function上面戴帽子[ 🎩 ]
提供額外的訊息和觸發特定的行為。
[SerializeField]:
[SerializeField]
private int myPrivateField;
[HideInInspector]:
[HideInInspector]
public int myPublicField;
[Range(min, max)]:
[Range(0, 100)]
public int myRangeField;
[Tooltip("Description")]:
[Tooltip("This is a tooltip")]
public int myField;
[Header("Header Title")]:
[Header("My Header")]
public int myField;
[Space(height)]:
[Space(10)]
public int myField;
[Multiline]:
[Multiline]
public string myString;
[TextArea(minLines, maxLines)]:
[TextArea(3, 10)]
public string myString;
[RequireComponent(typeof(Component))]:
[RequireComponent(typeof(Rigidbody))]
public class MyComponent : MonoBehaviour
{
// ...
}
[AddComponentMenu("Menu Name")]:
[AddComponentMenu("Custom/MyComponent")]
public class MyComponent : MonoBehaviour
{
// ...
}
[ExecuteInEditMode]:
[ExecuteInEditMode]
public class MyComponent : MonoBehaviour
{
// ...
}
[DisallowMultipleComponent]:
[DisallowMultipleComponent]
public class MyComponent : MonoBehaviour
{
// ...
}
[SelectionBase]:
[SelectionBase]
public class MyComponent : MonoBehaviour
{
// ...
}
[RuntimeInitializeOnLoadMethod]:
RuntimeInitializeLoadType.AfterSceneLoad
或 RuntimeInitializeLoadType.BeforeSceneLoad
。using UnityEngine;
public class MyClass
{
[RuntimeInitializeOnLoadMethod]
static void OnRuntimeMethodLoad()
{
Debug.Log("This runs when the game starts.");
}
[RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
static void BeforeSceneLoad()
{
Debug.Log("This runs before any scene is loaded.");
}
}
[InitializeOnLoadMethod]:
using UnityEditor;
using UnityEngine;
public class MyEditorClass
{
[InitializeOnLoadMethod]
static void OnEditorLoad()
{
Debug.Log("This runs when the editor loads.");
}
}
[MenuItem]:
using UnityEditor;
using UnityEngine;
public class MyMenuItems
{
[MenuItem("MyMenu/Do Something")]
static void DoSomething()
{
Debug.Log("Doing something...");
}
[MenuItem("MyMenu/Do Something with Shortcut %g")]
static void DoSomethingWithShortcut()
{
Debug.Log("Doing something with shortcut...");
}
}
[CustomEditor]:
創建自定義編輯器,讓你自定義Inspector的顯示效果
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(MyComponent))]
public class MyComponentEditor : Editor
{
public override void OnInspectorGUI()
{
DrawDefaultInspector();
MyComponent myComponent = (MyComponent)target;
if (GUILayout.Button("Do Something"))
{
myComponent.DoSomething();
}
}
}
[Test]:
-標記Unit Test方法。
using NUnit.Framework;
public class MyTests
{
[Test]
public void MyTest()
{
Assert.AreEqual(1, 1);
}
}
[UnityTest]:
標記一個協程測試方法。
using UnityEngine.TestTools;
using NUnit.Framework;
using System.Collections;
public class MyUnityTests
{
[UnityTest]
public IEnumerator MyUnityTest()
{
yield return null;
Assert.AreEqual(1, 1);
}
}
如果你有使用第三方的插件
如Odin Inspector,
裡面會提供更多的Inspector擴展Attribute可以快速使用。
你可以創建自己的屬性來添加特定的元數據或行為。創建自定義屬性需要繼承 System.Attribute
並使用 [AttributeUsage]
指定屬性可以應用到哪些目標。
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyCustomAttribute : Attribute
{
public string Description { get; }
public MyCustomAttribute(string description)
{
Description = description;
}
}
如何自製作自己的 Attribute:
using System;
using System.Reflection;
using UnityEngine;
public class DataNameAttribute : Attribute
{
public string PropName;
}
在需要更換名字的變數上加入DataName的Attribute,
複寫ToString的函式
public class Character
{
[DataName(PropName = "LifePoint")]
public int Hp { get; set; }
[DataName]
public int Mp { get; set; }
public override string ToString()
{
string str = "";
foreach (PropertyInfo info in GetType().GetProperties())
{
foreach (Attribute attr in Attribute.GetCustomAttributes(info))
{
if (attr.GetType() == typeof(DataNameAttribute))
{
var propName = ((DataNameAttribute)attr).PropName;
if (propName != null)
str += ((DataNameAttribute)attr).PropName + ":" + info.GetValue(this) + " ";
else
str += info.Name + ":" + info.GetValue(this) + " ";
}
}
}
return str;
}
}
public class CharacterData : MonoBehaviour
{
private void Start()
{
Character character = new Character();
character.Hp = 100;
character.Mp = 200;
Debug.Log(character);
}
}
5.顯示結果: