5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GetComponentで誤解してた

Posted at

GetComponentは継承を考慮してくれるっぽい

class TestA : MonoBehaviour {
   ...
}
class TestB : TestA {
   ...
}

と定義されたスクリプトを、GameObjectにアタッチし、

var a = testB.GetComponent<TestA>();
Debug.Log("testB.GetComponent<TestA>()->"+a );
var b = testB.GetComponent<TestB>();
Debug.Log("testB.GetComponent<TestB>()->"+b );

とした場合、

go.GetComponent<TestA>()->TestGameObject (TestB)
go.GetComponent<TestB>()->TestGameObject (TestB)

と、継承を考慮して返してくれる。無駄な処理を減らせる。

スクリプトは一つのGameObjectに、同じクラスでも複数アタッチできるっぽい。

var scripts = go.GetComponents<MonoBehaviour>();

で、全てのスクリプトをとってこれるっぽいな。(あんまり使い道はないが)
同じ系統のスクリプトは一つのみとかに制限する処理とか

Debug.Assert( go.GetComponents<TestA>().Length<=1 );

とかしてやればいいみたい。


放っておくと毎日何もしないので、せめて週1くらいでは何か残すぞ

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?