本日は Unity の小ネタ枠です。
Unity で親オブジェクトや子オブジェクトのスクリプトの参照を取得する方法を記事にします。
参照の優先度
GetComponentInParent または GetComponentInChildren での参照の動作と優先度を確認するため、以下のサンプルコードを作成しました。
・GetParentTest.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GetParentTest : MonoBehaviour
{
[ContextMenu("ParentTest")]
public void GetComponentInParentTest()
{
Debug.Log("ParentTest");
this.GetComponentInParent<CheckObject>().ShowObjectName();
}
[ContextMenu("ChildrenTest")]
public void GetComponentInChildrenTest()
{
Debug.Log("ChildrenTest");
this.GetComponentInChildren<CheckObject>().ShowObjectName();
}
}
・CheckObject.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CheckObject : MonoBehaviour
{
public void ShowObjectName()
{
Debug.Log("ObjectName : " + this.transform.name);
}
}
以下のように各オブジェクトに CheckObject.cs を設定します。
![f:id:bluebirdofoz:20220219233055j:plain](https://cdn-ak.f.st-hatena.com/images/fotolife/b/bluebirdofoz/20220219/20220219233055.jpg)
中央の ThisObject にのみ GetParentTest.cs を設定して動作確認を実施してみました。
![f:id:bluebirdofoz:20220219233106j:plain](https://cdn-ak.f.st-hatena.com/images/fotolife/b/bluebirdofoz/20220219/20220219233106.jpg)
GetComponentInParentによる親オブジェクトの参照
有効なコンポーネントを検出するまで上方へ再帰呼び出しを行います。
親オブジェクトを辿るように捜索が行われるため、以下の通り実行オブジェクトから最も近い親オブジェクトの参照が返ります。
![f:id:bluebirdofoz:20220219233115j:plain](https://cdn-ak.f.st-hatena.com/images/fotolife/b/bluebirdofoz/20220219/20220219233115.jpg)
GetComponentInChildrenによる子オブジェクトの参照
有効なコンポーネントを検出するまで深さ優先探索を行います。
子オブジェクトを辿るように捜索が行われるため、こちらも以下の通り実行オブジェクトから最も近い親オブジェクトの参照が返ります。
![f:id:bluebirdofoz:20220219233123j:plain](https://cdn-ak.f.st-hatena.com/images/fotolife/b/bluebirdofoz/20220219/20220219233123.jpg)
捜索開始オブジェクトに該当スクリプトがある場合
捜索開始オブジェクトに該当スクリプトがある場合はどちらも同オブジェクトの参照が返ります。
![f:id:bluebirdofoz:20220219233131j:plain](https://cdn-ak.f.st-hatena.com/images/fotolife/b/bluebirdofoz/20220219/20220219233131.jpg)
GetComponentInChildrenによる深さ優先探索の動き
同じ階層の子オブジェクトは Hierarchy 上で上方に配置されているオブジェクトから参照が返ります。
![f:id:bluebirdofoz:20220219233140j:plain](https://cdn-ak.f.st-hatena.com/images/fotolife/b/bluebirdofoz/20220219/20220219233140.jpg)
![f:id:bluebirdofoz:20220219233149j:plain](https://cdn-ak.f.st-hatena.com/images/fotolife/b/bluebirdofoz/20220219/20220219233149.jpg)
また深さ優先探索のため、より深い階層のオブジェクトであっても Hierarchy 上で上方に位置するオブジェクトが先に検出されます。
以下は ChildObject02 と ChildObject03 にのみ CheckObject.cs を設定したケースです。
![f:id:bluebirdofoz:20220219233157j:plain](https://cdn-ak.f.st-hatena.com/images/fotolife/b/bluebirdofoz/20220219/20220219233157.jpg)