facebook twitter hatena line email

Unity/EditorWindow/GameObjectをPrefabに変更

提供: 初心者エンジニアの簡易メモ
移動: 案内検索

全シーンの、指定したGameObjectをPrefabに変更するコード

using UnityEditor;
using UnityEngine;
using UnityEditor.SceneManagement;
using UnityEngine.SceneManagement;
using System.IO;
using System.Text;

public class ReplaceObjectWithPrefab : EditorWindow
{
    private string directoryPath = "Assets/Scenes";  // デフォルト値
    private string objectName = "ReturnButton";      // デフォルト値
    private GameObject prefab;

    [MenuItem("Tools/Replace Object With Prefab")]
    public static void ShowWindow()
    {
        GetWindow<ReplaceObjectWithPrefab>("Replace Object With Prefab");
    }

    private void OnGUI()
    {
        GUILayout.Label("Directory and Object Settings", EditorStyles.boldLabel);

        directoryPath = EditorGUILayout.TextField("Directory Path", directoryPath);
        objectName = EditorGUILayout.TextField("Object Name", objectName);
        prefab = (GameObject)EditorGUILayout.ObjectField("Prefab", prefab, typeof(GameObject), false);

        if (GUILayout.Button("Replace Objects in Scenes"))
        {
            ReplaceObjectsInScenes();
        }
    }

    private void ReplaceObjectsInScenes()
    {
        if (string.IsNullOrEmpty(directoryPath) || string.IsNullOrEmpty(objectName) || prefab == null)
        {
            Debug.LogError("Please specify the directory path, object name, and prefab.");
            return;
        }

        // 現在のシーンを保存し、シーンパスを記録
        Scene currentScene = EditorSceneManager.GetActiveScene();
        string currentScenePath = currentScene.path;

        if (currentScene.isDirty)
        {
            EditorSceneManager.SaveScene(currentScene);
        }

        // ディレクトリ内のすべてのシーンファイルを取得
        string[] sceneFiles = Directory.GetFiles(directoryPath, "*.unity", SearchOption.AllDirectories);

        foreach (string scenePath in sceneFiles)
        {
            // シーンを開く
            Scene scene = EditorSceneManager.OpenScene(scenePath);

            if (!scene.IsValid())
            {
                Debug.LogError($"Invalid scene path: {scenePath}");
                continue;
            }

            // オブジェクトを探す
            GameObject targetObject = GameObject.Find(objectName);

            if (targetObject == null)
            {
                Debug.LogWarning($"Object '{objectName}' not found in scene: {scenePath}");
                continue;
            }

            // ヒエラルキーでの位置情報を保持する
            RectTransform targetRectTransform = targetObject.GetComponent<RectTransform>();
            Vector3 localPosition = targetRectTransform.localPosition;
            Quaternion localRotation = targetObject.transform.localRotation;
            Vector3 localScale = targetObject.transform.localScale;
            int siblingIndex = targetObject.transform.GetSiblingIndex();
            Canvas canvas = targetRectTransform.GetComponentInParent<Canvas>();

            // プレハブをインスタンス化
            GameObject newObject = (GameObject)PrefabUtility.InstantiatePrefab(prefab, scene);
            RectTransform newRectTransform = newObject.GetComponent<RectTransform>();

            // 新しいオブジェクトを元の位置に配置する
            newRectTransform.SetParent(targetRectTransform.parent, false);
            newRectTransform.localPosition = localPosition;  // 同じ位置に配置
            newObject.transform.localRotation = localRotation;
            newObject.transform.localScale = localScale;
            newObject.transform.SetSiblingIndex(siblingIndex);

            // 旧オブジェクトを削除
            DestroyImmediate(targetObject);

            // ヒエラルキーパスを生成
            string hierarchyPath = GetHierarchyPath(newObject);

            // シーンパスとヒエラルキーパスをログに出力
            Debug.Log($"Replaced object in scene: {scenePath}\nHierarchy Path: {hierarchyPath}");

            // シーンを保存する
            EditorSceneManager.MarkSceneDirty(scene);
            EditorSceneManager.SaveScene(scene);
        }

        // 最後に元のシーンを再度開く
        if (!string.IsNullOrEmpty(currentScenePath))
        {
            EditorSceneManager.OpenScene(currentScenePath);
        }
    }

    // ヒエラルキーパスを生成するメソッド
    private string GetHierarchyPath(GameObject obj)
    {
        StringBuilder path = new StringBuilder(obj.name);
        Transform current = obj.transform.parent;

        while (current != null)
        {
            path.Insert(0, $"{current.name}/");
            current = current.parent;
        }

        return path.ToString();
    }
}