1
0

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 3 years have passed since last update.

Unity コンポーネントを持っているかを調べる

Posted at

##0.0 はじめに
ゲームオブジェクトに特定のコンポーネントが含まれているか調べる

##1.0 結論
GetComponent<>()の返り値で判断可能です。
例えばゲームオブジェクトにRigidbodyコンポーネントが含まれていればGetComponent< Rigidbody>()の返り値はtrue、含まれてなければ返り値はfalseとなります。、

Test.cs
if (GetComponent<Rigidbody2D>()) {
    Debug.Log("Rigidbody2D含まれてるよ");
} else {
    Debug.Log("Rigidbody2D含まれてないよ");
    gameObject.AddComponent<Rigidbody2D>(); // 含まれてなければ加える
}

##2.0 おまけ
下記のように[RequireComponent (typeof ())]のアトリビュートを付けているとコンポーネントを自動に追加してくれます。
ポスト typeof ()の()中にコンポーネント名を入れる。

Test.cs
[RequireComponent (typeof (Rigidbody))]
public class Test : MonoBehaviour {

}
1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?