Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
1
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

@r83s

プレハブを一括で修正するエディタスクリプト

大量生産されたプレハブを機械的にいじる機会がちょいちょいあるので書いてみた。

public class PrefabChanger
{
    public static void ExecuteChange(List<string> targets, System.Action<GameObject> onChange)
    {
        if (onChange == null) return;

        foreach (string path in targets)
        {
            var prefabAsset = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
            if (prefabAsset == null) continue;

            var prefab = PrefabUtility.InstantiatePrefab(prefabAsset) as GameObject;
            if (prefab == null) continue;

            onChange(prefab);
            PrefabUtility.ReplacePrefab(prefab, prefabAsset);    // 反映.

            GameObject.DestroyImmediate(prefab);
        }
    }

    // 子どものGameObjectを走査して処理を適用するためのヘルパ.
    public static void ScanTree(GameObject gameObj, System.Action<GameObject> onExecute)
    {
        if (gameObj == null) return;
        if (onExecute == null) return;

        onExecute(gameObj);

        if (gameObj.transform.childCount > 0)
        {
            for (int i = 0; i < gameObj.transform.childCount; ++i)
            {
                var child = gameObj.transform.GetChild(i);
                ScanTree(child.gameObject, onExecute);
            }
        }
    }
}

使い方

List<string> targets = new List<string>();
// ディレクトリパスを指定.
targets.Add("Assets/Prefabs/PrefabA.prefab");
targets.Add("Assets/Prefabs/PrefabB.prefab");
targets.Add("Assets/Resources/Prefabs/Prefab01.prefab");
targets.Add("Assets/Resources/Prefabs/Prefab02.prefab");

PrefabChanger.ExecuteChange(targets, prefab => {
    // 新しい子ノードを追加してあげたりとか、
    GameObject child = new GameObject();
    child.transform.parent = prefab.transform;
    // 要らなくなったコンポーネントを削除するとか、
    PrefabChanger.ScanTree(prefab, gameObj => {
        GameObject.DestroyImmediate(gameObj.GetComponent<Hoge>());
    });
});
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
1
Help us understand the problem. What are the problem?