Processing / Javaでプログラムを書いています。
UnityのGetComponent<T>()のような指定したクラスの型のComponentを取得するメソッドが書けません。
Processing
1class TG_GameObject extends TG_Object{ 2 ArrayList<TG_Component> components = new ArrayList<TG_Component>(); 3 public <T> T AddComponent(TG_Component component){ 4 component.gameObject = this; 5 components.add(component); 6 return (T)component; 7 } 8 public <T> T GetComponent(int i){ 9 return components.size() > i ? (T)components.get(i) : null; 10 } 11 public <T> T GetComponent(){ 12 for(TG_Component component: components){ 13 // コンパイルエラー。どうしたら。。。 14 if(component instanceof T){ 15 return (T).component; 16 } 17 } 18 return null; 19 } 20}
Unity風な気持ち的には
Processing
1MyRigidbody r = GetComponent<MyRigidBody>();
こんな風にGameObjectのArrayListに溜め込んだComponentから、指定した型のインスタンスが取得できたらいいのですが。
あるいは、別の切り口でGetComponentする方法があればご教示ください。
なお、Javaもジェネリックもよくわかっていません。
(ご質問への回答)
ArrayListで使っている型のTG_Componentと、各メソッドの総称型のTはどのような関係を想定しているのでしょうか?
回答になっているかわからないのですが、関係性がわかるかな?というプログラムを(シューティングゲームを作るような想定で)書いてみました。
伝わらなかったらすみません。。
class Player extends TG_GameObject{ Player(){ AddComponent(new Ship()); AddComponent(new Bullet()); } } class Ship extends TG_Component{ public TG_GameObject gameObject; // 所属するgameObject public void update(){ // 所属するgameObjectにAddされているBulletというComponentを探す(これがやりたい!) gameObject.GetComponent<Bullet>().shot(); } } class Bullet extends TG_Component{ public TG_GameObject gameObject; public void shot(){ render(); } }
回答1件
あなたの回答
tips
プレビュー