MRが楽しい

MRやVRについて学習したことを書き残す

UnityでHierarchy階層の一番上のオブジェクトを参照する

本日はUnityの小ネタ枠です。
UnityでHierarchy階層の一番上のオブジェクトを参照する方法についてです。

Transform.root

Transform.rootはそのTransformの階層の一番上のTransformの参照を返します。
また、そのTransform自身が一番上のTransformである場合は自身のTransformを返します。

var rootTransform = transform.root

docs.unity3d.com

サンプルスクリプト

transform.rootで取得したTransformが自身か否かをチェックすることで自身が階層の一番上のオブジェクトか否かを判定する以下のサンプルスクリプトを作成しました。
・HierarchyRootTest.cs

using UnityEngine;

public class HierarchyRootTest : MonoBehaviour
{
    [ContextMenu("CheckHierarchyRoot")]
    public void CheckHierarchyRoot()
    {
        var hierarchyRoot = transform.root;
        
        // 取得したルートオブジェクトが自身のtransformと一致する場合は階層の一番上のオブジェクトと判定する
        if (hierarchyRoot == transform)
        {
            Debug.Log("This object is the top of the hierarchy.");
        }
        else
        {
            Debug.Log($"Hierarchy Root: {hierarchyRoot.name}");
        }
    }
}

階層の一番上のオブジェクトに本コンポーネントをアタッチしてCheckHierarchyRoot関数を実行すると、階層の一番上のオブジェクトと判定します。

それ以外のオブジェクトで実行した場合はその階層の一番上のオブジェクト名を表示します。