動的に追加するコンポーネントを選択
コンポーネントを追加する際に、状況に応じて追加したいコンポーネントを変える方法。
C#ではClass型を変数に格納することはできないので(?)、typeof()でその型がもつType型(型宣言)が取得できる。UnityではAddComponent<T>()の他にAddComponent(Type componentType)があるので、生成したいコンポーネントをType型で渡してあげれば動的に追加するコンポーネントが選べる。
(そもそもこんなやり方でいいのかな…)
using System;
using UnityEngine;
public class TypeTest : MonoBehaviour {
ComponentChoser compChoser = new ComponentChoser();
void Start() {
this.gameObject.AddComponent(this.compChoser.ChoseComponent());
}
}
/// <summary>
/// コンポーネントを選んでくれる。
/// </summary>
public class ComponentChoser {
enum ComponentType {
TypeA,
TypeB,
TypeC
}
ComponentType createType = ComponentType.TypeB;
public Type ChoseComponent() {
Type t = null;
switch (this.createType) {
case ComponentType.TypeA:
t = typeof(A);
break;
case ComponentType.TypeB:
t = typeof(B);
break;
case ComponentType.TypeC:
t = typeof(C);
break;
}
return t;
}
}
/// <summary>
/// 作られるコンポーネント。
/// </summary>
public abstract class Base : MonoBehaviour {}
public class A : Base {}
public class B : Base {}
public class C : Base {}
コメントを残す