この文書の現在のバージョンと選択したバージョンの差分を表示します。
両方とも前のリビジョン 前のリビジョン 次のリビジョン | 前のリビジョン | ||
wiki:unity:tips:098 [2015/02/12 13:01] step |
— (現在) | ||
---|---|---|---|
ライン 1: | ライン 1: | ||
- | ====== 098 セーフティーなAddComponent /GetComponent ====== | ||
- | |||
- | ===== 概要 ===== | ||
- | よく使う機能はラップしておくとより安全に使えます。 | ||
- | |||
- | <code csharp> | ||
- | //------------------------------------------------------------- | ||
- | //! コンポーネントの追加(存在チェック版). | ||
- | //------------------------------------------------------------- | ||
- | static public T AddSafeComponent<T>(GameObject _go) where T : Component | ||
- | { | ||
- | T component = _go.GetComponent<T>(); | ||
- | if (component == null) | ||
- | { | ||
- | // 無ければ足す。 | ||
- | return _go.AddComponent<T>(); | ||
- | } | ||
- | // あればそのまま返す。 | ||
- | return component; | ||
- | } | ||
- | |||
- | //------------------------------------------------------------- | ||
- | //! コンポーネントの取得(存在チェック版). | ||
- | //------------------------------------------------------------- | ||
- | public static T GetSafeComponent<T>(GameObject _go) where T : Component | ||
- | { | ||
- | T component = _go.GetComponent<T>(); | ||
- | |||
- | if(component == null) | ||
- | { | ||
- | Debug.LogError("Expected to find component of type " + typeof(T) + " but found none.", _go); | ||
- | } | ||
- | return component; | ||
- | } | ||
- | </code> | ||