3
3

Unity 6でGameObjectにGetComponentCount、GetComponentAtIndex、GetComponentIndexメソッドが追加された

Posted at

Unity 6 Previewで、GameObjectクラスに次のメソッドが追加されました。

また、Componentクラスに次のメソッドが追加されました。

using UnityEngine;

public class Sample : MonoBehaviour
{
    private void Start()
    {
        // 新メソッドのGetComponentCount
        // 対象GameObjectに付与されているComponentの数を取得
        // Transform Componentも数に含まれる点に注意
        var componentCount = gameObject.GetComponentCount();
        
        for (var index = 0; index < componentCount; index++)
        {
            // GetComponentAtIndexで指定indexのComponentを取得できる
            // GetComponentAtIndexには、ジェネリックバージョンもある
            // 公式ドキュメントには「nullも返しえる」ってあるけれど、例外投げる見たいだからnull返す?
            var targetComponent = gameObject.GetComponentAtIndex(index);
            Debug.Log($"targetComponent is {targetComponent.GetType().Name}.");

            // GetComponentIndexで、引数のComponentのindexを取得できる
            // ※ targetComponentIndexはindexと同じはずだから、実質無駄な呼び出し
            var targetComponentIndex = gameObject.GetComponentIndex(targetComponent);
            Debug.Log($"targetComponent index is {targetComponentIndex}.");
        }
        // ※ ↑処理は、新しいメソッドでなくても、GetComponentsを使えば代替できる

        // 次のGetComponentIndexはGameObjectクラスでなく、ComponentクラスのGetComponentIndex
        Debug.Log($"{GetType().Name} index is {GetComponentIndex()}");
    }
}

なお、これらのメソッドは最新のLTSであるUnity 2022.3.20にもバックポートされ、追加されているようです。公式ドキュメントであるUnity 2023.3のScript Referenceにも、該当メソッドが追加されています。(パッチバージョンでAPIが追加されていることに注意してください、Unity 2022.3.19では使えませんでした。)

ちなみに、Unity 6 Previewの前テックリリースバージョン相当である、Unity 2023.2には、これらのメソッドは追加されていません。

3
3
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
3
3