Unity: AddComponentで追加するコンポーネントを動的に変更する
初歩的なことかもしれませんが、
スクリプトから追加するコンポーネントを動的に変更しようとして、
少し詰まったので記録を残しておきます。
解決法
public Component AddComponent(Type componentType)
へ追加するクラスをTypeとして渡すことで実現できます。
AddComponentに渡すType型は、typeof(クラスの型)で取得できます。
サンプルコード
例えばMonobehaviourを継承したHogeクラスと、
さらにそのHogeクラスを継承したSubHogeAとSubHogeBというクラスがあるとします。
ランダムにコンポーネントとして追加するクラスを変更したいといったとき、
以下のようなコードで実現できます。
using System; using UnityEngine; public class Main : MonoBehaviour { void Awake (){ int random = UnityEngine.Random.Range(0, 3); Type type; switch(random) { case 0: type = typeof(Hoge); break; case 1: type = typeof(SubHogeA); break; case 2: type = typeof(SubHogeB); break; default: type = null; break; } if(type != null) { Hoge hogeInstance = gameObject.AddComponent(type) as Hoge; // "ほげ~", "ほげほげ~", "ほげほげほげ"のうち、 // どれかがランダムに表示される hogeInstance.SaySomething(); } } } public class Hoge: MonoBehaviour { public virtual void SaySomething() { Debug.Log ("ほげ~"); } } public class SubHogeA: Hoge { public override void SaySomething() { Debug.Log ("ほげほげ~"); } } public class SubHogeB: Hoge { public override void SaySomething() { Debug.Log ("ほげほげほげ"); } }