9
26

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】GetComponent<>って何を取得しているか

Last updated at Posted at 2022-01-23

Unityでよく見る GetCompoent<> が何なのかよくわかっていなかったので備忘録として記事にいたしました。

完全個人メモです。

そもそもUnityにおけるComponentとは?

Unityの概念として GameObject という「物/入れ物」に対して、Component は「物」の見た目や振る舞いなどの機能群を提供する「部品」になります。

GameObject に紐づいている Component を確認するには、「Inspector」の欄を確認します。

Screen Shot 2022-01-23 at 20.07.31.png

上記、赤枠部分が「Cube」という GameObject に紐づいている Component = 部品 です。

この場合、Mesh Renderer Box Collider などが、CubeというGameObjectに紐づいているComponent ということになります。

「Add Component」とあるように、必要な部品を適宜追加していきます。

では、GetComponent<>とは?

では、本題の GetComponent<> とは?ですが、先ほどお伝えした GameBojectに紐づいているComponent を指定して取得します。

using UnityEngine;

public class Sample : MonoBehaviour
{
    public MeshRenderer meshRenderer;

    private void Start()
    {
        // アタッチされているGameObjectのComponentから「MeshRenderer」を取得する
        meshRenderer = GetComponent<MeshRenderer>();

        // 取得できた「MeshRenderer」に対して、Scriptで動的に操作する
    }
}

そして、どのGameObjectから取得するのか ですが、
このScriptがアタッチされているGameObjectからになります。

GameObjectを取得するには?

ここまでは、Componentの取得方法 でした。

では、GameObjectの取得方法 はどのようになるのでしょうか?

それはいくつかの方法があります。

GameObject.Find

これは、シーン内に存在するゲームオブジェクトの名前で取得します。
名前は完全一致で取得するので、動作の負荷としては高いです。

GameObject.FindWithTag

これはGameObject.FindWithTagの複数オブジェクトを取得するバージョンです。
タグの性質上、複数のオブジェクトに同一のタグを保有することがよくあるので、検索するタグを持つオブジェクトをすべて取得します。
なので、返り値は配列となっており、該当するものがない場合はからの配列が帰ってきます。

まとめ

  • UnityにおけるComponentは、GameObjectに紐づいた部品である
  • GetComponent<>は、アタッチされたGameObjectの中から指定したComponentを取得するためのもの
  • GameObjectを取得するものではない
  • GameObjectの取得は、「Find/FindWithTag」がある

参考文献

以上となります。

9
26
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
9
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?