對組件的動態操作
編譯階段自動添加組件
使用RequireComponent標籤標記一個MonoBehaviour,則這個組件被附加到一個GameObject上時會檢測是否已經附加了前置組件,如果沒有,則自動添加前置組件。
[RequireComponent(typeof(CharactorController))]
public class UnitManager : MonoBehaviour
{
}
動態處理組件
- 使用AddComponent給GameObject附加組件:
public T GameObject.AddComponent<T>();
public Component GameObject.AddComponent(Type componentType);
示例:下列三種用法結果是一致的
void Start()
{
GameObject player = GameObject.Find("Player");
PlayerController pc = player.AddComponent<PlayerController>();
// PlayerController pc = player.AddComponent(typeof(PlayerController)) as PlayerController;
// PlayerController pc = player.AddComponent(System.Type.GetType("PlayerController")) as PlayerController;
}
public T GameObject.GetComponent<T>();
public Component GameObject.GetComponent(Type type);
public Component GameObject.GetComponent(string type);
public T[] GameObject.GetComponents<T>();
public Component[] GameObject.GetComponents(Type type);
public T GameObject.GetComponentInChildren<T>(bool includeInactive = false);
public T GameObject.GetComponentInParent<T>(bool includeInactive = false);
public T[] GameObject.GetComponentsInChildren<T>(bool includeInactive = false);
public T[] GameObject.GetComponentsInParent<T>(bool includeInactive = false);
注:對一個GameObject嘗試獲取一個基類,可以返回該類的派生類。
public static void GameObject.Destroy(Component cpn);
public static void GameObject.Destroy(Component cpn, float delay);
和GameObject一致,可以設定刪除的延遲時間。
由於this指向自己,所以組件可以做到刪除自己:
Destroy(this);
通過樹型結構和反射寫法,Unity提供了一個廣播機制繞過多態編程調用組件上的函數。它們的作用是在不需要知道組件名稱的情況下,調用組件中的方法。
public void Component.SendMessage(string methodName, object value = null);
public void Component.BroadcastMessage(string methodName, object value = null);
public void Component.SendMessageUpwards(string methodName, object value = null);
SendMessage可以作用於該組件所附加的GameObject,遍歷該GameObject上的所有組件,調用每個組件中的每一個名爲methodName的public方法。使用廣播調用方法時,可以填入一個任意類型的參數,也可以沒有參數。如果想通過廣播調用具有多個參數的方法,可以將參數打包爲結構體,並重載一個單參數版本。
BroadcastMessage作用於該組件所附加的GameObject及其所有子結點,併產生和SendMessage一致的效果。
SendMessageUpwards作用於該組件所附加的GameObject及其父節點,併產生和SendMessage一致的效果。