コガネブログ

平日更新を目標に Unity や C#、Visual Studio、ReSharper などのゲーム開発アレコレを書いていきます

【Unity】自分自身を含むすべての子オブジェクトのレイヤーを設定する拡張メソッド

ソースコード

using UnityEngine;

public static class GameObjectExtensions
{
    /// <summary>
    /// 自分自身を含むすべての子オブジェクトのレイヤーを設定します
    /// </summary>
    public static void SetLayerRecursively( 
        this GameObject self, 
        int layer 
    )
    {
        self.layer = layer;
        
        foreach ( Transform n in self.transform )
        {
            SetLayerRecursively( n.gameObject, layer );
        }
    }
}

使い方

gameObject.SetLayerRecursively( 8 );

関連記事