コガネブログ

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

【Unity】指定したフォルダ内のプレハブを一括で編集するスクリプトのテンプレート

スクリプト

using System.Linq;
using UnityEditor;
using UnityEngine;

internal static class Example
{
    [MenuItem( "Tools/Hoge" )]
    private static void Hoge()
    {
        const string directoryName = "Assets/";

        var assetPaths = AssetDatabase
                .GetAllAssetPaths()
                .Where( x => x.StartsWith( directoryName ) )
                .Where( x => AssetDatabase.LoadAssetAtPath<GameObject>( x ) != null )
                .ToArray()
            ;

        try
        {
            AssetDatabase.StartAssetEditing();

            foreach ( var assetPath in assetPaths )
            {
                using var editingScope = new PrefabUtility.EditPrefabContentsScope( assetPath );
                var       prefabRoot   = editingScope.prefabContentsRoot;
                var       transforms   = prefabRoot.GetComponentsInChildren<Transform>();

                if ( transforms.Length <= 0 ) continue;

                // TODO:
            }
        }
        finally
        {
            AssetDatabase.StopAssetEditing();
        }
    }
}